Completed
Pull Request — master (#34)
by Fèvre
05:12 queued 02:29
created

PostController::delete()   B

Complexity

Conditions 5
Paths 9

Size

Total Lines 34
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 34
rs 8.439
c 0
b 0
f 0
cc 5
eloc 21
nc 9
nop 1
1
<?php
2
namespace Xetaravel\Http\Controllers\Discuss;
3
4
use Carbon\Carbon;
5
use Illuminate\Http\RedirectResponse;
6
use Illuminate\Http\Request;
7
use Illuminate\Support\Facades\Auth;
8
use Xetaio\Mentions\Parser\MentionParser;
9
use Xetaravel\Models\DiscussConversation;
10
use Xetaravel\Models\DiscussPost;
11
use Xetaravel\Models\Repositories\DiscussPostRepository;
12
use Xetaravel\Models\Repositories\DiscussUserRepository;
13
use Xetaravel\Models\User;
14
use Xetaravel\Models\Validators\DiscussPostValidator;
15
16
class PostController extends Controller
17
{
18
    /**
19
     * Create a post for a conversation.
20
     *
21
     * @param \Illuminate\Http\Request $request
22
     *
23
     * @return \Illuminate\Http\RedirectResponse
24
     */
25
    public function create(Request $request): RedirectResponse
26
    {
27
        $conversation = DiscussConversation::findOrFail($request->conversation_id);
0 ignored issues
show
Unused Code introduced by
$conversation is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
28
29
        if (DiscussPost::isFlooding('xetaravel.flood.discuss.post')) {
30
            return back()
31
                ->withInput()
32
                ->with('danger', 'Wow, keep calm bro, and try to not flood !');
33
        }
34
35
        DiscussPostValidator::create($request->all())->validate();
36
        $post = DiscussPostRepository::create($request->all());
37
        $user = DiscussUserRepository::create($request->all());
0 ignored issues
show
Unused Code introduced by
$user is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
38
39
        $parser = new MentionParser($post);
40
        $content = $parser->parse($post->content);
41
42
        $post->content = $content;
43
        $post->save();
44
45
        return redirect()
46
            ->route('discuss.post.show', ['id' => $post->getKey()])
47
            ->with('success', 'Your reply has been posted successfully !');
48
    }
49
50
    /**
51
     * Redirect an user to a conversation, page and post.
52
     *
53
     * @param \Illuminate\Http\Request $request
54
     * @param int $id The ID of the post.
55
     *
56
     * @return \Illuminate\Http\RedirectResponse
57
     */
58 View Code Duplication
    public function show(Request $request, int $id): RedirectResponse
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...
59
    {
60
        $post = DiscussPost::findOrFail($id);
61
62
        $postsBefore = DiscussPost::where([
63
            ['conversation_id', $post->conversation_id],
64
            ['created_at', '<', $post->created_at]
65
        ])->count();
66
67
        $postsPerPage = config('xetaravel.pagination.discuss.post_per_page');
68
69
        $page = floor($postsBefore / $postsPerPage) + 1;
70
        $page = ($page > 1) ? $page : 1;
71
72
        $request->session()->keep(['primary', 'danger', 'warning', 'success', 'info']);
0 ignored issues
show
Bug introduced by
The method keep() does not seem to exist on object<Symfony\Component...ssion\SessionInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
73
74
        return redirect()
75
            ->route(
76
                'discuss.conversation.show',
77
                [
78
                    'slug' => $post->conversation->slug,
79
                    'id' => $post->conversation->id,
80
                    'page' => $page,
81
                    '#post-' . $post->getKey()
82
                ]
83
            );
84
    }
85
86
    /**
87
     * Handle a delete action for the post.
88
     *
89
     * @param \Illuminate\Http\Request $request
0 ignored issues
show
Bug introduced by
There is no parameter named $request. 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...
90
     * @param int $id
91
     *
92
     * @return \Illuminate\Http\RedirectResponse
93
     */
94
    public function delete(int $id): RedirectResponse
95
    {
96
        $post = DiscussPost::findOrFail($id);
97
        $conversation = $post->conversation;
98
99
        if ($conversation->first_post_id == $post->getKey()) {
100
            return redirect()
101
                ->route('discuss.post.show', ['id' => $post->getKey()])
102
                ->with('danger', 'You can not deete the first post of a conversation !');
103
        }
104
105
        if ($conversation->last_post_id == $post->getKey()) {
106
            $previousPost = DiscussPostRepository::findPreviousPost($post);
107
108
            $conversation->last_post_id = $previousPost->getKey();
109
        }
110
111
        if ($conversation->solved_post_id == $post->getKey()) {
112
            $conversation->solved_post_id = null;
113
            $conversation->is_solved = false;
114
        }
115
116
        if ($post->delete()) {
117
            $conversation->save();
118
119
            return redirect()
120
                ->route('discuss.conversation.show', ['id' => $conversation->getKey(), 'slug' => $conversation->slug])
121
                ->with('success', 'This post has been deleted successfully !');
122
        }
123
124
        return redirect()
125
            ->route('discuss.post.show', ['id' => $post->getKey()])
126
            ->with('danger', 'An error occurred while deleting this post !');
127
    }
128
129
    /**
130
     * Mark as solved.
131
     *
132
     * @param int $id
133
     *
134
     * @return \Illuminate\Http\RedirectResponse
135
     */
136
    public function solved(int $id): RedirectResponse
137
    {
138
        $post = DiscussPost::findOrFail($id);
139
140
        if ($post->getKey() == $post->conversation->solved_post_id) {
141
            return back()
142
                ->with('danger', 'This post is already the solved post !');
143
        }
144
145
        if (!is_null($post->conversation->solved_post_id)) {
146
            return back()
147
                ->with('danger', 'This conversation has already a solved post !');
148
        }
149
        $conversation = DiscussConversation::findOrFail($post->conversation_id);
150
151
        $conversation->solved_post_id = $post->getKey();
152
        $conversation->is_solved = true;
153
        $conversation->save();
154
155
        return redirect()
156
            ->route('discuss.conversation.show', ['slug' => $conversation->slug, 'id' => $conversation->getKey()])
157
            ->with('success', 'This reply as been marked as solved !');
158
    }
159
160
    /**
161
     * Handle an edit action for the post.
162
     *
163
     * @param Request $request
164
     * @param int $id The id of the post to edit.
165
     *
166
     * @return \Illuminate\Http\RedirectResponse
167
     */
168
    public function edit(Request $request, int $id) : RedirectResponse
169
    {
170
        $post = DiscussPost::findOrFail($id);
171
172
        if (!Auth::user()->can('update', $post)) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Illuminate\Contracts\Auth\Authenticatable as the method can() does only exist in the following implementations of said interface: Illuminate\Foundation\Auth\User, Tests\vendor\Models\User, Xetaravel\Models\User.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
173
            return back()
174
                ->with('danger', 'You\'re not authorized to edit this message.');
175
        }
176
177
        DiscussPostValidator::edit($request->all())->validate();
178
179
        $parser = new MentionParser($post);
180
        $content = $parser->parse($request->input('content'));
0 ignored issues
show
Bug introduced by
It seems like $request->input('content') targeting Illuminate\Http\Concerns...ractsWithInput::input() can also be of type array; however, Xetaio\Mentions\Parser\MentionParser::parse() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
181
182
        $post->content = $content;
183
        $post->is_edited = true;
184
        $post->edited_user_id = Auth::id();
185
        $post->edited_at = Carbon::now();
186
        $post->save();
187
188
        return redirect()
189
            ->route('discuss.post.show', ['id' => $id])
190
            ->with('success', 'Your post has been edited successfully !');
191
    }
192
193
    /**
194
     * Get the edit json template.
195
     *
196
     * @param int $id
197
     *
198
     * @return \Illuminate\Http\JsonResponse|\Illuminate\View\View
0 ignored issues
show
Documentation introduced by
Should the return type not be \Symfony\Component\HttpFoundation\Response?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
199
     */
200
    public function editTemplate(int $id)
201
    {
202
        $post = DiscussPost::find($id);
203
204
        if (!Auth::user()->can('update', $post) || !$post) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Illuminate\Contracts\Auth\Authenticatable as the method can() does only exist in the following implementations of said interface: Illuminate\Foundation\Auth\User, Tests\vendor\Models\User, Xetaravel\Models\User.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
205
            return response()->json([
206
                'error' => true,
207
                'message' => 'You\'re not authorized to edit this message or this message has been deleted.'
208
            ]);
209
        }
210
211
        return response(
212
            view('Discuss::post.editTemplate', ['post' => $post]),
0 ignored issues
show
Documentation introduced by
view('Discuss::post.edit...array('post' => $post)) is of type object<Illuminate\View\V...Contracts\View\Factory>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
213
            200,
214
            ['Content-Type' => 'application/json']
215
        );
216
    }
217
}
218