Completed
Push — master ( 8877d3...488134 )
by Reto
01:30
created

LaravelBlogController   A

Complexity

Total Complexity 42

Size/Duplication

Total Lines 230
Duplicated Lines 36.52 %

Coupling/Cohesion

Components 2
Dependencies 7

Importance

Changes 0
Metric Value
wmc 42
lcom 2
cbo 7
dl 84
loc 230
rs 9.0399
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
A index() 0 6 1
A create() 0 9 1
B store() 13 44 5
B showSlug() 4 21 6
B showYearMonthSlug() 21 21 6
B showYearMonthDaySlug() 20 20 6
B showID() 4 22 7
A edit() 0 9 1
B update() 15 44 6
A destroy() 0 7 1
A admin_page() 0 6 1
A indexAuthor() 7 7 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like LaravelBlogController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use LaravelBlogController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Retosteffen\LaravelBlog\Http\Controllers;
4
5
use App\User;
6
use Illuminate\Http\Request;
7
use Retosteffen\LaravelBlog\Models\Category;
8
use Retosteffen\LaravelBlog\Models\LaravelBlog;
9
use Spatie\Tags\Tag;
10
11
class LaravelBlogController
12
{
13
    public function index()
14
    {
15
        $posts = LaravelBlog::where('published', '=', true)->orderBy('published_at', 'desc')->get();
16
17
        return view('laravel-blog::blog.index', compact('posts'));
18
    }
19
20
    public function create(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

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

Loading history...
21
    {
22
        //$this->authorize('create',[LaravelBlog::class]);
23
24
        $tags = Tag::all()->sortBy('name', SORT_NATURAL | SORT_FLAG_CASE);
25
        $categories = Category::all()->sortBy('name', SORT_NATURAL | SORT_FLAG_CASE);
26
27
        return view('laravel-blog::blog.create', compact('tags', 'categories'));
28
    }
29
30
    public function store(Request $request)
31
    {
32
        //$this->authorize('create',[LaravelBlog::class]);
33
        $attributes = request()->validate([
34
            'title'=>['required', 'regex:/^(?![0-9]*$)[a-zA-Z0-9 \-]+$/'],
35
            'content'=>['required'],
36
            'excerpt'=>['max:158'],
37
            'image' => ['image', 'mimes:jpeg,png,jpg,gif,svg', 'max:2048'],
38
            'alt_text'=>[],
39
        ]);
40
        $attributes['published'] = request()->has('published');
41
42
        if (request()->has('published')) {
43
            $attributes['published_at'] = date('Y-m-d H:i:s');
44
        }
45
46
        $blog_post = LaravelBlog::create($attributes);
47
        $blog_post->author()->associate(auth()->user());
0 ignored issues
show
Bug introduced by
The method user does only exist in Illuminate\Contracts\Auth\Guard, but not in Illuminate\Contracts\Auth\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...
48
        $blog_post->category()->associate(request()->get('category'));
49
        $blog_post->save();
50
51
        $image_path = null;
52 View Code Duplication
        if ($request->file('image')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
53
            $original_file_name=$request->file('image')->getClientOriginalName();
54
            $image_path = $request->file('image')->storeAs('blog_posts/'.$blog_post->id,$original_file_name, 'public');
55
        }
56
        $blog_post->image = $image_path;
57
        $blog_post->save();
58
59
60
        $tags_array = $request->get('tags');
61
        $tags_names_array = [];
62 View Code Duplication
        if ($tags_array) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
63
            foreach ($tags_array as $tag_id) {
64
                $tag_object = Tag::find($tag_id);
65
                $tags_names_array[] = $tag_object->name;
66
            }
67
            $blog_post->syncTagsWithType($tags_names_array);
68
        } else {
69
            $blog_post->syncTags([]);
70
        }
71
72
        return redirect()->route('blog_admin');
73
    }
74
75
    public function showSlug(LaravelBlog $blogPost)
76
    {
77
        if (! $blogPost->published && ! auth()->user()) {
0 ignored issues
show
Bug introduced by
The method user does only exist in Illuminate\Contracts\Auth\Guard, but not in Illuminate\Contracts\Auth\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...
78
            abort(404);
79
        }
80
81
        if (config('laravel-blog.permalink') == 'year/month/slug') {
82
            return redirect()->route('showYearMonthSlug', ['year'=>\Carbon\Carbon::parse($blogPost->published_at)->year, 'month'=>\Carbon\Carbon::parse($blogPost->published_at)->month, 'blogPost' => $blogPost->slug]
83
      );
84
        }
85 View Code Duplication
        if (config('laravel-blog.permalink') == 'year/month/day/slug') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
86
            return redirect()->route('showYearMonthDaySlug', ['year'=>\Carbon\Carbon::parse($blogPost->published_at)->year, 'month'=>\Carbon\Carbon::parse($blogPost->published_at)->month, 'day'=>\Carbon\Carbon::parse($blogPost->published_at)->day, 'blogPost' => $blogPost->slug]
87
      );
88
        }
89
        if (config('laravel-blog.permalink') == 'id') {
90
            return redirect()->route('showID', ['id' => $blogPost->id]
91
      );
92
        }
93
94
        return view('laravel-blog::blog.show', compact('blogPost'));
95
    }
96
97 View Code Duplication
    public function showYearMonthSlug($year, $month, LaravelBlog $blogPost)
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
        if (! $blogPost->published && ! auth()->user()) {
0 ignored issues
show
Bug introduced by
The method user does only exist in Illuminate\Contracts\Auth\Guard, but not in Illuminate\Contracts\Auth\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...
100
            abort(404);
101
        }
102
103
        if (config('laravel-blog.permalink') == 'slug') {
104
            return redirect()->route('showSlug', ['blogPost' => $blogPost->slug]
105
      );
106
        }
107
        if (config('laravel-blog.permalink') == 'id') {
108
            return redirect()->route('showID', ['id' => $blogPost->id]
109
      );
110
        }
111
        if (config('laravel-blog.permalink') == 'year/month/day/slug') {
112
            return redirect()->route('showYearMonthDaySlug', ['year'=>$year, 'month'=>$month, 'day'=>\Carbon\Carbon::parse($blogPost->published_at)->day, 'blogPost' => $blogPost->slug]
113
      );
114
        }
115
116
        return view('laravel-blog::blog.show', compact('blogPost'));
117
    }
118
119 View Code Duplication
    public function showYearMonthDaySlug($year, $month, $day, LaravelBlog $blogPost)
0 ignored issues
show
Unused Code introduced by
The parameter $day is not used and could be removed.

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

Loading history...
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...
120
    {
121
        if (! $blogPost->published && ! auth()->user()) {
0 ignored issues
show
Bug introduced by
The method user does only exist in Illuminate\Contracts\Auth\Guard, but not in Illuminate\Contracts\Auth\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...
122
            abort(404);
123
        }
124
        if (config('laravel-blog.permalink') == 'slug') {
125
            return redirect()->route('showSlug', ['blogPost' => $blogPost->slug]
126
      );
127
        }
128
        if (config('laravel-blog.permalink') == 'id') {
129
            return redirect()->route('showID', ['id' => $blogPost->id]
130
      );
131
        }
132
        if (config('laravel-blog.permalink') == 'year/month/slug') {
133
            return redirect()->route('showYearMonthSlug', ['year'=>$year, 'month'=>$month, 'blogPost' => $blogPost->slug]
134
      );
135
        }
136
137
        return view('laravel-blog::blog.show', compact('blogPost'));
138
    }
139
140
    public function showID($id)
141
    {
142
        $blogPost = LaravelBlog::find($id);
143
        if ($blogPost && ! $blogPost->published && ! auth()->user()) {
0 ignored issues
show
Bug introduced by
The method user does only exist in Illuminate\Contracts\Auth\Guard, but not in Illuminate\Contracts\Auth\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...
144
            abort(404);
145
        }
146
147
        if (config('laravel-blog.permalink') == 'slug') {
148
            return redirect()->route('showSlug', ['blogPost' => $blogPost->slug]
149
      );
150
        }
151
        if (config('laravel-blog.permalink') == 'year/month/slug') {
152
            return redirect()->route('showYearMonthSlug', ['year'=>\Carbon\Carbon::parse($blogPost->published_at)->year, 'month'=>\Carbon\Carbon::parse($blogPost->published_at)->month, 'blogPost' => $blogPost->slug]
153
      );
154
        }
155 View Code Duplication
        if (config('laravel-blog.permalink') == 'year/month/day/slug') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
156
            return redirect()->route('showYearMonthDaySlug', ['year'=>\Carbon\Carbon::parse($blogPost->published_at)->year, 'month'=>\Carbon\Carbon::parse($blogPost->published_at)->month, 'day'=>\Carbon\Carbon::parse($blogPost->published_at)->day, 'blogPost' => $blogPost->slug]
157
      );
158
        }
159
160
        return view('laravel-blog::blog.show', compact('blogPost'));
161
    }
162
163
    public function edit(LaravelBlog $blogPost)
164
    {
165
        //$this->authorize('update',$blogPost);
166
167
        $tags = Tag::all()->sortBy('name', SORT_NATURAL | SORT_FLAG_CASE);
168
        $categories = Category::all()->sortBy('name', SORT_NATURAL | SORT_FLAG_CASE);
169
170
        return view('laravel-blog::blog.edit', compact('blogPost', 'tags', 'categories'));
171
    }
172
173
    public function update(Request $request, LaravelBlog $blogPost)
174
    {
175
        //$this->authorize('update',$blogPost);
176
        $attributes = request()->validate([
177
            'title'=>['required', 'regex:/^(?![0-9]*$)[a-zA-Z0-9 \-]+$/'],
178
            'content'=>['required'],
179
            'excerpt'=>['max:158'],
180
            'image' => ['image', 'mimes:jpeg,png,jpg,gif,svg', 'max:2048'],
181
            'alt_text'=>[],
182
        ]);
183
        $attributes['published'] = request()->has('published');
184
185 View Code Duplication
        if ($request->file('image')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
186
            $original_file_name=$request->file('image')->getClientOriginalName();
187
            $image_path = $request->file('image')->storeAs('blog_posts/'.$blogPost->id,$original_file_name, 'public');
188
        } else {
189
            $image_path = $blogPost->image;
190
        }
191
192
        if ($blogPost->published == false && request()->has('published')) {
193
            $attributes['published_at'] = date('Y-m-d H:i:s');
194
        }
195
196
        $blogPost->category()->associate(request()->get('category'));
197
198
        $tags_array = $request->get('tags');
199
        $tags_names_array = [];
200 View Code Duplication
        if ($tags_array) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
201
            foreach ($tags_array as $tag_id) {
202
                $tag_object = Tag::find($tag_id);
203
                $tags_names_array[] = $tag_object->name;
204
            }
205
            $blogPost->syncTagsWithType($tags_names_array);
206
        } else {
207
            $blogPost->syncTags([]);
208
        }
209
210
        $blogPost->update($attributes);
211
212
        $blogPost->image = $image_path;
213
        $blogPost->save();
214
215
        return redirect()->route('blog_admin');
216
    }
217
218
    public function destroy(LaravelBlog $blogPost)
219
    {
220
        //$this->authorize('destroy',$blogPost);
221
        $blogPost->delete();
222
223
        return redirect()->route('blog_admin');
224
    }
225
226
    public function admin_page()
227
    {
228
        $posts = LaravelBlog::orderBy('published_at', 'desc')->get();
229
230
        return view('laravel-blog::blog_admin', compact('posts'));
231
    }
232
233 View Code Duplication
    public function indexAuthor($user_name)
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...
234
    {
235
        $item = User::where('name', '=', $user_name)->first();
236
        $posts = LaravelBlog::where('published', '=', true)->where('user_id', '=', $item->id)->orderBy('published_at', 'desc')->get();
237
238
        return view('laravel-blog::archive', compact('item', 'posts'));
239
    }
240
}
241