Completed
Push — master ( c7e879...390e33 )
by Fèvre
02:26
created

DiscussConversationRepository::update()   D

Complexity

Conditions 10
Paths 68

Size

Total Lines 39
Code Lines 22

Duplication

Lines 6
Ratio 15.38 %

Importance

Changes 0
Metric Value
dl 6
loc 39
rs 4.8196
c 0
b 0
f 0
cc 10
eloc 22
nc 68
nop 2

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace Xetaravel\Models\Repositories;
3
4
use Carbon\Carbon;
5
use Illuminate\Support\Collection;
6
use Illuminate\Support\Facades\Auth;
7
use Xetaravel\Events\Discuss\CategoryWasChangedEvent;
8
use Xetaravel\Events\Discuss\ConversationWasLockedEvent;
9
use Xetaravel\Events\Discuss\ConversationWasPinnedEvent;
10
use Xetaravel\Events\Discuss\TitleWasChangedEvent;
11
use Xetaravel\Models\DiscussConversation;
12
use Xetaravel\Models\DiscussPost;
13
use Xetaravel\Models\DiscussUser;
14
15
class DiscussConversationRepository
16
{
17
18
    /**
19
     * Create the new conversation and save it.
20
     *
21
     * @param array $data The data used to create the conversation.
22
     *
23
     * @return \Xetaravel\Models\DiscussConversation
24
     */
25
    public static function create(array $data): DiscussConversation
26
    {
27
        $conversation = [
28
            'title' => $data['title'],
29
            'category_id' => $data['category_id']
30
        ];
31
32
        $user = Auth::user();
33
34
        if ($user->hasPermission('manage.discuss.conversations')) {
35
            $conversation += [
36
                'is_locked' => isset($data['is_locked']) ? true : false,
37
                'is_pinned' => isset($data['is_pinned']) ? true : false,
38
            ];
39
        }
40
41
        $conversation = DiscussConversation::create($conversation);
42
43
        $comment = DiscussPost::create([
44
            'conversation_id' => $conversation->id,
45
            'content' => $data['content']
46
        ]);
47
48
        $participant = DiscussUser::create([
0 ignored issues
show
Unused Code introduced by
$participant 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...
49
            'conversation_id' => $conversation->id,
50
            'is_read' => 1
51
        ]);
52
53
        $conversation->first_post_id = $comment->id;
54
        $conversation->last_post_id = $comment->id;
55
        $conversation->save();
56
57
        return $conversation;
58
    }
59
60
    /**
61
     * Update the conversation data and save it.
62
     *
63
     * @param array $data The data used to update the conversation.
64
     * @param \Xetaravel\Models\DiscussConversation $conversation The conversation to update.
65
     *
66
     * @return \Xetaravel\Models\DiscussConversation
67
     */
68
    public static function update(array $data, DiscussConversation $conversation): DiscussConversation
69
    {
70
        if (Auth::user()->hasPermission('manage.discuss.conversations')) {
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...
71
            $data['is_pinned'] = isset($data['is_pinned']) ? true : false;
72
            $data['is_locked'] = isset($data['is_locked']) ? true : false;
73
74 View Code Duplication
            if ($conversation->is_pinned != $data['is_pinned'] && $data['is_pinned'] == 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...
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...
75
                event(new ConversationWasPinnedEvent($conversation, Auth::user()));
0 ignored issues
show
Unused Code introduced by
The call to ConversationWasPinnedEvent::__construct() has too many arguments starting with \Illuminate\Support\Facades\Auth::user().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
76
            }
77
78 View Code Duplication
            if ($conversation->is_locked != $data['is_locked'] && $data['is_locked'] == 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...
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...
79
                event(new ConversationWasLockedEvent($conversation, Auth::user()));
0 ignored issues
show
Unused Code introduced by
The call to ConversationWasLockedEvent::__construct() has too many arguments starting with \Illuminate\Support\Facades\Auth::user().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
80
            }
81
82
            $conversation->is_locked = $data['is_locked'];
83
            $conversation->is_pinned = $data['is_pinned'];
84
        }
85
86
        if ($conversation->title != $data['title']) {
87
            event(new TitleWasChangedEvent($conversation, $data['title'], $conversation->title));
88
89
            $conversation->title = $data['title'];
90
        }
91
92
        if ($conversation->category_id != $data['category_id']) {
93
            event(new CategoryWasChangedEvent($conversation, $data['category_id'], $conversation->category_id));
94
95
            $conversation->category_id = $data['category_id'];
96
        }
97
98
        $conversation->is_edited = true;
99
        $conversation->edit_count++;
100
        $conversation->edited_user_id = Auth::id();
101
        $conversation->edited_at = Carbon::now();
102
103
        $conversation->save();
104
105
        return $conversation;
106
    }
107
}
108