Passed
Push — master ( 2c7b25...f52af3 )
by Mihail
05:14
created

CommentAnswerAdd   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 114
Duplicated Lines 26.32 %

Coupling/Cohesion

Components 1
Dependencies 15

Importance

Changes 4
Bugs 1 Features 0
Metric Value
c 4
b 1
f 0
dl 30
loc 114
rs 9.1666
wmc 22
lcom 1
cbo 15

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A before() 7 7 2
C check() 23 51 13
B buildRecord() 0 27 6

How to fix   Duplicated Code   

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:

1
<?php
2
3
namespace Apps\Model\Api\Comments;
4
5
6
use Apps\ActiveRecord\CommentAnswer;
7
use Apps\ActiveRecord\CommentPost;
8
use Apps\Model\Front\Profile\EntityAddNotification;
9
use Ffcms\Core\App;
10
use Ffcms\Core\Arch\Model;
11
use Ffcms\Core\Exception\JsonException;
12
use Ffcms\Core\Helper\Date;
13
use Ffcms\Core\Helper\Text;
14
use Ffcms\Core\Helper\Type\Str;
15
16
/**
17
 * Class CommentAnswerAdd. Model to add comment answer to database and build response active record row.
18
 * @package Apps\Model\Api\Comments
19
 */
20
class CommentAnswerAdd extends Model
21
{
22
    public $message;
23
    public $replayTo = 0;
24
    public $guestName;
25
    public $ip;
26
27
    private $_configs;
28
    private $_userId = 0;
29
30
    public function __construct(array $configs)
31
    {
32
        $this->_configs = $configs;
33
        parent::__construct();
34
    }
35
36 View Code Duplication
    public function before()
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...
37
    {
38
        $this->ip = App::$Request->getClientIp();
39
        if (App::$User->isAuth()) {
40
            $this->_userId = App::$User->identity()->getId();
41
        }
42
    }
43
44
    /**
45
     * Check if comment answer conditions is ok. Will throw exception if not.
46
     * @return bool
47
     * @throws JsonException
48
     */
49
    public function check()
50
    {
51
        // check if user is auth'd or guest name is defined
52 View Code Duplication
        if (!App::$User->isAuth() && ((int)$this->_configs['guestAdd'] !== 1 || Str::length($this->guestName) < 2)) {
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
            throw new JsonException(__('Guest name is not defined'));
54
        }
55
56
        // guest moderation
57 View Code Duplication
        if (!App::$User->isAuth() && (bool)$this->_configs['guestModerate']) {
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...
58
            $captcha = App::$Request->request->get('captcha');
59
            if (!App::$Captcha->validate($captcha)) {
60
                throw new JsonException(__('Captcha is incorrect! Click on image to refresh and try again'));
61
            }
62
        }
63
64
        // check if replayTo is defined
65
        if ($this->replayTo < 1) {
66
            throw new JsonException(__('Comment post thread is not founded'));
67
        }
68
69
        // check if message length is correct
70 View Code Duplication
        if (Str::length($this->message) < (int)$this->_configs['minLength'] || Str::length($this->message) > (int)$this->_configs['maxLength']) {
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...
71
            throw new JsonException(__('Message length is incorrect. Current: %cur%, min - %min%, max - %max%', [
72
                'cur' => Str::length($this->message),
73
                'min' => $this->_configs['minLength'],
74
                'max' => $this->_configs['maxLength']
75
            ]));
76
        }
77
78
        $count = CommentPost::where('id', '=', $this->replayTo)->count();
79
        if ($count !== 1) {
80
            throw new JsonException(__('Comment post thread is not founded'));
81
        }
82
83
        // check to prevent spam
84
        $query = CommentAnswer::where('user_id', '=', $this->_userId)
85
            ->orWhere('ip', '=', $this->ip)
86
            ->orderBy('created_at', 'DESC')
87
            ->first();
88
89
        // something is founded :D
90 View Code Duplication
        if ($query !== null) {
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...
91
            $answerTime = Date::convertToTimestamp($query->created_at);
92
            $delay = $answerTime + $this->_configs['delay'] - time();
93
            if ($delay > 0) { // sounds like config time is not passed now
94
                throw new JsonException(__('Spam protection: please, wait %sec% seconds', ['sec' => $delay]));
95
            }
96
        }
97
98
        return true;
99
    }
100
101
    /**
102
     * Add comment answer to database and return active record object
103
     * @return CommentAnswer
104
     */
105
    public function buildRecord()
106
    {
107
        $record = new CommentAnswer();
108
        $record->comment_id = $this->replayTo;
109
        $record->user_id = $this->_userId;
110
        $record->guest_name = $this->guestName;
111
        $record->message = $this->message;
112
        $record->lang = App::$Request->getLanguage();
113
        $record->ip = $this->ip;
114
        // check if premoderation is enabled and user is guest
115
        if ((bool)$this->_configs['guestModerate'] && $this->_userId < 1) {
116
            $record->moderate = 1;
117
        }
118
        $record->save();
119
120
        // add notification for comment post owner
121
        $commentPost = $record->getCommentPost();
122
        if ($commentPost !== null && (int)$commentPost->user_id !== 0 && (int)$commentPost->user_id !== $this->_userId) {
123
            $notify = new EntityAddNotification((int)$commentPost->user_id);
0 ignored issues
show
Documentation introduced by
(int) $commentPost->user_id is of type integer, but the function expects a boolean.

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...
124
            $notify->add($commentPost->pathway, EntityAddNotification::MSG_ADD_COMMENTANSWER, [
125
                'snippet' => Text::snippet(App::$Security->strip_tags($this->message), 50),
0 ignored issues
show
Bug introduced by
It seems like \Ffcms\Core\App::$Securi...ip_tags($this->message) targeting Ffcms\Core\Helper\Security::strip_tags() can also be of type array; however, Ffcms\Core\Helper\Text::snippet() 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...
126
                'post' => Text::snippet(App::$Security->strip_tags($commentPost->message), 50)
0 ignored issues
show
Bug introduced by
It seems like \Ffcms\Core\App::$Securi...($commentPost->message) targeting Ffcms\Core\Helper\Security::strip_tags() can also be of type array; however, Ffcms\Core\Helper\Text::snippet() 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...
127
            ]);
128
        }
129
130
        return $record;
131
    }
132
133
}