Completed
Push — fix-various-bugs ( de2bba )
by Fèvre
02:31
created

ConversationController::create()   B

Complexity

Conditions 3
Paths 2

Size

Total Lines 25
Code Lines 16

Duplication

Lines 7
Ratio 28 %

Importance

Changes 0
Metric Value
dl 7
loc 25
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 16
nc 2
nop 1
1
<?php
2
namespace Xetaravel\Http\Controllers\Discuss;
3
4
use Illuminate\Http\Request;
5
use Illuminate\Http\RedirectResponse;
6
use Illuminate\Support\Facades\Auth;
7
use Illuminate\View\View;
8
use Xetaio\Mentions\Parser\MentionParser;
9
use Xetaravel\Models\DiscussCategory;
10
use Xetaravel\Models\DiscussConversation;
11
use Xetaravel\Models\DiscussLog;
12
use Xetaravel\Models\Repositories\DiscussConversationRepository;
13
use Xetaravel\Models\Validators\DiscussConversationValidator;
14
15
class ConversationController extends Controller
16
{
17
    /**
18
     * Show the conversation by its id.
19
     *
20
     * @return \Illuminate\Http\Response
0 ignored issues
show
Documentation introduced by
Should the return type not be View|\Illuminate\Contracts\View\Factory?

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...
21
     */
22
    public function show(Request $request, string $slug, int $id)
0 ignored issues
show
Unused Code introduced by
The parameter $slug 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...
23
    {
24
        $conversation = DiscussConversation::findOrFail($id);
25
        $categories = DiscussCategory::pluckLocked('title', 'id');
26
27
        $posts = $conversation->posts()
28
            ->where('id', '!=', $conversation->solved_post_id)
29
            ->where('id', '!=', $conversation->first_post_id)
30
            ->paginate(config('xetaravel.pagination.discuss.post_per_page'));
31
32
        $postsWithLogs = $conversation->getPostsWithLogs(
33
            collect($posts->items()),
34
            $this->getCurrentPage($request)
35
        );
36
37
        $this->breadcrumbs->setListElementClasses('breadcrumbs');
38
        $breadcrumbs = $this->breadcrumbs->addCrumb(e($conversation->title), $conversation->conversation_url);
39
40
        return view(
41
            'Discuss::conversation.show',
42
            compact('conversation', 'posts', 'postsWithLogs', 'breadcrumbs', 'categories')
43
        );
44
    }
45
46
    /**
47
     * Show the create form.
48
     *
49
     * @return \Illuminate\View\View
50
     */
51
    public function showCreateForm(): View
52
    {
53
        $categories = DiscussCategory::pluckLocked('title', 'id');
54
55
        $breadcrumbs = $this->breadcrumbs->addCrumb('Start a discussion', route('discuss.conversation.create'));
56
57
        return view('Discuss::conversation.create', compact('breadcrumbs', 'categories'));
58
    }
59
60
    /**
61
     * Handle a conversation create request for the application.
62
     *
63
     * @param \Illuminate\Http\Request $request
64
     *
65
     * @return \Illuminate\Http\RedirectResponse
66
     */
67
    public function create(Request $request)
68
    {
69
        DiscussConversationValidator::create($request->all())->validate();
70
71
        // Users that have the permission "manage.discuss" can bypass this rule. (Default to Administrator)
72 View Code Duplication
        if (DiscussConversation::isFlooding('xetaravel.flood.discuss.conversation') &&
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...
73
            !Auth::user()->hasPermission('manage.discuss')
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 hasPermission() does only exist in the following implementations of said interface: 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...
74
        ) {
75
            return back()
76
                ->withInput()
77
                ->with('danger', 'Wow, keep calm bro, and try to not flood !');
78
        }
79
        $conversation = DiscussConversationRepository::create($request->all());
80
        $post = $conversation->firstPost;
81
82
        $parser = new MentionParser($post);
83
        $content = $parser->parse($post->content);
84
85
        $post->content = $content;
86
        $post->save();
87
88
        return redirect()
89
            ->route('discuss.conversation.show', ['slug' => $conversation->slug, 'id' => $conversation->getKey()])
90
            ->with('success', 'Your discussion has been created successfully !');
91
    }
92
93
    /**
94
     * Handle a conversation update request for the application.
95
     *
96
     * @param \Illuminate\Http\Request $request
97
     * @param string $slug The slug of the conversation to update.
98
     * @param int $id The id of the conversation to update.
99
     *
100
     * @return \Illuminate\Http\RedirectResponse
101
     */
102
    public function update(Request $request, string $slug, int $id)
0 ignored issues
show
Unused Code introduced by
The parameter $slug 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...
103
    {
104
        $conversation = DiscussConversation::findOrFail($id);
105
106
        $this->authorize('update', $conversation);
107
108
        DiscussConversationValidator::update($request->all(), $id)->validate();
109
        $conversation = DiscussConversationRepository::update($request->all(), $conversation);
110
111
        return redirect()
112
            ->route('discuss.conversation.show', ['slug' => $conversation->slug, 'id' => $conversation->getKey()])
113
            ->with('success', 'Your discussion has been updated successfully !');
114
    }
115
116
    /**
117
     * Handle the delete request for a conversation.
118
     *
119
     * @param string $slug The slug of the conversation to delete.
120
     * @param int $id The id of the conversation to delete.
121
     *
122
     * @return \Illuminate\Http\RedirectResponse
123
     */
124
    public function delete(string $slug, int $id) : RedirectResponse
0 ignored issues
show
Unused Code introduced by
The parameter $slug 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...
125
    {
126
        $conversation = DiscussConversation::findOrFail($id);
127
128
        $this->authorize('delete', $conversation);
129
130
        if ($conversation->delete()) {
131
            return redirect()
132
                ->route('discuss.index')
133
                ->with('success', 'This discussion has been deleted successfully !');
134
        }
135
136
        return back()
137
            ->with('danger', 'An error occurred while deleting this discussion !');
138
    }
139
140
    /**
141
     * Get the current page for the conversation.
142
     *
143
     * @param \Illuminate\Http\Request $request
144
     *
145
     * @return int
146
     */
147
    protected function getCurrentPage(Request $request): int
148
    {
149
        return !is_null($request->get('page')) ? (int)$request->get('page') : 1;
150
    }
151
}
152