Completed
Push — master ( 1ea504...c9b7a6 )
by Faiq
26s
created

ArticleController::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace App\Http\Controllers;
4
5
use App\Common;
6
use Illuminate\Http\Request;
7
Use Illuminate\Support\Facades\Storage;
8
use Illuminate\Support\Facades\Auth;
9
use App\Articles;
10
11
class ArticleController extends Controller
12
{
13
    /**
14
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
15
     */
16
    public function index()
17
    {
18
        $articles = Articles::orderBy('category','asc')->paginate(15);
19
        $data = [
20
            'articles' => $articles
21
        ];
22
23
        return view('pages.article')->with('data', $data);
24
    }
25
26
    /**
27
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
28
     */
29
    public function create()
30
    {
31
        return view('pages.ext.add-article');
32
    }
33
34
    /**
35
     * @param Request $request
36
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
37
     * @throws \Illuminate\Validation\ValidationException
38
     */
39
    public function store(Request $request)
40
    {
41
        $this->validate($request,[
42
            'category' => 'required',
43
            'title' => 'required',
44
            'content' => 'required|min:500',
45
            'cover_image' => 'image|nullable|max:3999'
46
        ]);
47
48
        if($request->hasFile('cover_image')){
49
            $filenameWithExt = $request->file('cover_image')->getClientOriginalName();
50
            $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
51
            $extension = $request->file('cover_image')->getClientOriginalExtension();
52
            $fileNameToStore = $filename.'_'.time().'.'.$extension;
53
            $path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);
0 ignored issues
show
Unused Code introduced by
The assignment to $path is dead and can be removed.
Loading history...
54
        }else {
55
            $fileNameToStore = 'noimage.jpg';
56
        }
57
58
        $article = new Articles;
59
        $article->category = $request->input('category');
60
        $article->title = $request->input('title');
61
        $article->content = $request->input('content');
62
        if(session('guard') == 'admin') {
63
            $article->admin_id = Auth::guard('admin')->user()->id;
64
        } else {
65
            $article->doctor_id = Auth::guard('doctor')->user()->id;
66
        }
67
        $article->cover_image = $fileNameToStore;
68
69
        $log = null;
70
        if($article->save()) {
71
            $log = Common::registerLog([
72
                'action' => "membuat artikel baru.",
73
                'target' => 'article',
74
                'prefix' => 'a-create',
75
                'target_id' => $article->id,
76
                'actor' => session('guard'),
77
                'actor_id' => Common::currentUser(session('guard'))->id
78
            ]);
79
        }
80
81
        if($log != null && $log == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
82
            return redirect (route(session('guard').'.article.index'))->with('success', 'Artikel baru berhasil ditambahkan !');
0 ignored issues
show
Bug introduced by
Are you sure session('guard') of type Illuminate\Session\Sessi...ate\Session\Store|mixed can be used in concatenation? ( Ignorable by Annotation )

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

82
            return redirect (route(/** @scrutinizer ignore-type */ session('guard').'.article.index'))->with('success', 'Artikel baru berhasil ditambahkan !');
Loading history...
83
        }
84
85
        return redirect(route(session('guard').'.article.create'))->with('failed', 'Gagal menambahkan artikel.');
86
    }
87
88
    /**
89
     * @param $id
90
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
91
     */
92
    public function show($id)
93
    {
94
        $article = Articles::find($id);
95
        if(!$article) {
96
            abort(404);
97
        }
98
        return view('pages.ext.view-article')->with('article', $article);
99
    }
100
101
    /**
102
     * @param $cat
103
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
104
     */
105
    public function listByCat($cat)
106
    {
107
        $category = null;
108
109
        switch ($cat) {
110
            case "penyakit":
111
                $category = "Penyakit";
112
                break;
113
            case "obat":
114
                $category = "Obat - obatan";
115
                break;
116
            case "hidup-sehat":
117
                $category = "Hidup Sehat";
118
                break;
119
            case "keluarga":
120
                $category = "Keluarga";
121
                break;
122
            case "kesehatan":
123
                $category = "Kesehatan";
124
                break;
125
        }
126
127
        $data = [
128
            'articles' => Articles::where('category', $cat)->orderBy('title','asc')->get(),
129
            'category' => $category,
130
            'cat' => $cat
131
        ];
132
133
        return view('articles')->with('data', $data);
134
    }
135
136
    public function listByName($cat, $name)
137
    {
138
        $category = null;
139
140
        switch ($cat) {
141
            case "penyakit":
142
                $category = "Penyakit";
143
                break;
144
            case "obat":
145
                $category = "Obat - obatan";
146
                break;
147
            case "hidup-sehat":
148
                $category = "Hidup Sehat";
149
                break;
150
            case "keluarga":
151
                $category = "Keluarga";
152
                break;
153
            case "kesehatan":
154
                $category = "Kesehatan";
155
                break;
156
        }
157
            $data = [
158
                'articles' => Articles::where('category', $cat)
159
                                        ->where('title','LIKE',$name.'%')
160
                                        ->orderBy('title','asc')
161
                                        ->get(),
162
                'category' => $category,
163
                'cat' => $cat
164
            ];
165
166
        return view('articles')->with('data', $data);
167
    }
168
169
    public function search(Request $request, $cat)
170
    {
171
        $cari = $request->cari;
172
        $articles = Articles::where('category', $cat)
173
                        ->where('content','LIKE','%'.$cari.'%')
174
                        ->orderBy('title','asc')
175
                        ->get();
176
        $category = null;
177
        switch ($cat) {
178
            case "penyakit":
179
                $category = "Penyakit";
180
                break;
181
            case "obat":
182
                $category = "Obat - obatan";
183
                break;
184
            case "hidup-sehat":
185
                $category = "Hidup Sehat";
186
                break;
187
            case "keluarga":
188
                $category = "Keluarga";
189
                break;
190
            case "kesehatan":
191
                $category = "Kesehatan";
192
                break;
193
        }
194
195
        $data = [
196
            'articles' => $articles,
197
            'category' => $category,
198
            'cat' => $cat
199
        ];
200
        return view('articles')->with('data', $data);
201
    }
202
203
    /**
204
     * @param $id
205
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
206
     */
207
    public function edit($id)
208
    {
209
        $article = Articles::find($id);
210
        if(!$article) {
211
            abort(404);
212
        }
213
214
        if($article->writer()['data']->id != Auth::guard(session('guard'))->user()->id) {
0 ignored issues
show
Bug introduced by
It seems like session('guard') can also be of type Illuminate\Session\SessionManager and Illuminate\Session\Store; however, parameter $name of Illuminate\Support\Facades\Auth::guard() does only seem to accept null|string, maybe add an additional type check? ( Ignorable by Annotation )

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

214
        if($article->writer()['data']->id != Auth::guard(/** @scrutinizer ignore-type */ session('guard'))->user()->id) {
Loading history...
215
            return redirect(session('guard').'/article')->with('warning', 'Anda tidak berhak untuk mengubah Artikel tersebut.');
0 ignored issues
show
Bug introduced by
Are you sure session('guard') of type Illuminate\Session\Sessi...ate\Session\Store|mixed can be used in concatenation? ( Ignorable by Annotation )

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

215
            return redirect(/** @scrutinizer ignore-type */ session('guard').'/article')->with('warning', 'Anda tidak berhak untuk mengubah Artikel tersebut.');
Loading history...
Bug Best Practice introduced by
The expression return redirect(session(...bah Artikel tersebut.') returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Contracts\Vie...ry|Illuminate\View\View.
Loading history...
216
        }
217
218
        $data = [
219
            'article' => $article
220
        ];
221
        return view('pages.ext.edit-article')->with('data', $data);
222
    }
223
224
    /**
225
     * @param Request $request
226
     * @param $id
227
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
228
     * @throws \Illuminate\Validation\ValidationException
229
     */
230
    public function update(Request $request, $id)
231
    {
232
        $this->validate($request,[
233
            'category' => 'required',
234
            'title' => 'required',
235
            'content' => 'required|min:500',
236
            'cover_image' => 'image|nullable|max:3999'
237
238
        ]);
239
240
        if($request->hasFile('cover_image')){
241
            $filenameWithExt = $request->file('cover_image')->getClientOriginalName();
242
            $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
243
            $extension = $request->file('cover_image')->getClientOriginalExtension();
244
            $fileNameToStore = $filename.'_'.time().'.'.$extension;
245
            $path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);
0 ignored issues
show
Unused Code introduced by
The assignment to $path is dead and can be removed.
Loading history...
246
        }
247
248
        $article = Articles::find($id);
249
        $article->category = $request->input('category');
250
        $article->title = $request->input('title');
251
        $article->content = $request->input('content');
252
        if($request->hasFile('cover_image')){
253
            $article->cover_image = $fileNameToStore;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $fileNameToStore does not seem to be defined for all execution paths leading up to this point.
Loading history...
254
        }
255
256
        $log = null;
257
        if($article->save()) {
258
            $log = Common::registerLog([
259
                'action' => "membuat perubahan pada artikelnya.",
260
                'target' => 'article',
261
                'prefix' => 'a-update',
262
                'target_id' => $article->id,
263
                'actor' => session('guard'),
264
                'actor_id' => Common::currentUser(session('guard'))->id
265
            ]);
266
        }
267
268
        if($log != null && $log == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
269
            return redirect (route(session('guard').'.article.index'))->with('success', 'Artikel berhasil diubah !');
0 ignored issues
show
Bug introduced by
Are you sure session('guard') of type Illuminate\Session\Sessi...ate\Session\Store|mixed can be used in concatenation? ( Ignorable by Annotation )

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

269
            return redirect (route(/** @scrutinizer ignore-type */ session('guard').'.article.index'))->with('success', 'Artikel berhasil diubah !');
Loading history...
270
        }
271
272
        return redirect (route(session('guard').'.article.edit', $id))->with('failed', 'Gagal mengubah artikel !');
273
    }
274
275
    /**
276
     * @param $id
277
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
278
     */
279
    public function destroy($id)
280
    {
281
        $article = Articles::find($id);
282
283
        if($article->cover_image != 'noimage.jpg'){
284
            Storage::delete('public/cover_images/'.$article->cover_image);
285
        }
286
287
        if($article->delete()) {
288
            return redirect()->back()->with('success', 'Artikel dihapus !');
289
        }
290
291
        return redirect()->back()->with('failed', 'Gagal menghapus artikel.');
292
    }
293
294
    /**
295
     * Get current logged in user
296
     *
297
     * @return mixed
298
     */
299
    private function currentUser() {
300
        return Auth::guard(session('guard'))->user();
0 ignored issues
show
Bug introduced by
It seems like session('guard') can also be of type Illuminate\Session\SessionManager and Illuminate\Session\Store; however, parameter $name of Illuminate\Support\Facades\Auth::guard() does only seem to accept null|string, maybe add an additional type check? ( Ignorable by Annotation )

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

300
        return Auth::guard(/** @scrutinizer ignore-type */ session('guard'))->user();
Loading history...
301
    }
302
}
303