Passed
Push — master ( d3fd5d...81f334 )
by Mihail
03:51
created

ActionMessageList::messageList()   D

Complexity

Conditions 13
Paths 15

Size

Total Lines 97
Code Lines 60

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
eloc 60
nc 15
nop 1
dl 0
loc 97
rs 4.9922
c 0
b 0
f 0

How to fix   Long Method    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
3
namespace Apps\Controller\Api\Profile;
4
5
use Apps\ActiveRecord\Blacklist;
6
use Apps\ActiveRecord\Message;
7
use Ffcms\Core\App;
8
use Ffcms\Core\Exception\ForbiddenException;
9
use Ffcms\Core\Exception\NativeException;
10
use Ffcms\Core\Exception\NotFoundException;
11
use Ffcms\Core\Helper\Date;
12
use Ffcms\Core\Helper\Type\Any;
13
use Ffcms\Core\Helper\Type\Arr;
14
use Ffcms\Core\Network\Request;
15
use Ffcms\Core\Network\Response;
16
17
/**
18
 * Class ActionMessageList
19
 * @package Apps\Controller\Api\Profile
20
 * @property Request $request
21
 * @property Response $response
22
 * @method void setJsonHeader
23
 */
24
trait ActionMessageList
25
{
26
    /**
27
     * List messages with correspondent
28
     * @param $corId
29
     * @return string
30
     * @throws ForbiddenException
31
     * @throws NotFoundException
32
     * @throws NativeException
33
     */
34
    public function messageList($corId): ?string
35
    {
36
        if (!App::$User->isAuth()) {
37
            throw new ForbiddenException('Auth required');
38
        }
39
40
        if (!Any::isInt($corId) || $corId < 1) {
41
            throw new NotFoundException('Corresponded id is wrong');
42
        }
43
44
        // get special types for this action
45
        $queryType = $this->request->get('type');
46
        $queryId = (int)$this->request->get('id');
47
        // get current user object
48
        $user = App::$User->identity();
49
50
        if (Arr::in($queryType, ['before', 'after']) && (!Any::isInt($queryId) || $queryId < 1)) {
51
            throw new NativeException('Bad input data');
52
        }
53
54
        $messages = null;
0 ignored issues
show
Unused Code introduced by
$messages 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...
55
        // sounds like a Hindi code, but we need more closures to organize where conditions
56
        // after raw: select * from `ffcms_messages` where `id` > ? and ((`target_id` = ? and `sender_id` = ?) or (`target_id` = ? and `sender_id` = ?)) order by `created_at` desc
0 ignored issues
show
Unused Code Comprehensibility introduced by
37% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
57
        // before raw: select * from `ffcms_messages` where (`target_id` = ? and `sender_id` = ?) or (`target_id` = ? and `sender_id` = ?) order by `created_at` desc
58
        // default raw: select * from `ffcms_messages` where `id` < ? and ((`target_id` = ? and `sender_id` = ?) or (`target_id` = ? and `sender_id` = ?)) order by `created_at` desc
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
59
        switch ($queryType) {
60
            case 'after':
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
61
                $messages = Message::where('id', '>', $queryId)
62
                    ->where(function ($query) use ($corId, $user) {
63
                        $query->where(function ($q) use ($cor_id, $user) {
0 ignored issues
show
Bug introduced by
The variable $cor_id does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
64
                            $q->where('target_id', '=', $user->getId())
65
                                ->where('sender_id', '=', $cor_id);
66
                        })->orWhere(function ($q) use ($cor_id, $user) {
67
                            $q->where('target_id', '=', $cor_id)
68
                                ->where('sender_id', '=', $user->getId());
69
                        });
70
                    });
71
                break;
72
            case 'before':
73
                $messages = Message::where('id', '<', $queryId)
74
                    ->where(function ($query) use ($corId, $user) {
75
                        $query->where(function ($q) use ($cor_id, $user) {
0 ignored issues
show
Bug introduced by
The variable $cor_id does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
76
                            $q->where('target_id', '=', $user->getId())
77
                                ->where('sender_id', '=', $cor_id);
78
                        })->orWhere(function ($q) use ($cor_id, $user) {
79
                            $q->where('target_id', '=', $cor_id)
80
                                ->where('sender_id', '=', $user->getId());
81
                        });
82
                    });
83
                break;
84
            default:
85
                $messages = Message::where(function ($query) use ($corId, $user) {
86
                    $query->where('target_id', '=', $user->getId())
87
                        ->where('sender_id', '=', $corId);
88
                })->orWhere(function ($query) use ($corId, $user) {
89
                    $query->where('target_id', '=', $corId)
90
                        ->where('sender_id', '=', $user->getId());
91
                });
92
                break;
93
        }
94
95
        // set response header
96
        $this->setJsonHeader();
0 ignored issues
show
Bug introduced by
It seems like setJsonHeader() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
97
98
        $messages->orderBy('created_at', 'DESC')
99
            ->take(self::MSG_TEXT_LIST);
100
101
        // check if messages exist
102
        if ($messages->count() < 1) {
103
            return json_encode(['status' => 0, 'text' => 'No messages']);
104
        }
105
106
        // build response
107
        $response = null;
108
        foreach ($messages->get() as $msg) {
109
            /** @var Message $msg */
110
            $response[] = [
111
                'id' => $msg->id,
112
                'my' => $msg->sender_id === $user->id,
113
                'message' => $msg->message,
114
                'date' => Date::convertToDatetime($msg->created_at, Date::FORMAT_TO_SECONDS),
115
                'readed' => $msg->readed
116
            ];
117
118
            // update status to readed
119
            if ((bool)$msg->readed !== true && $msg->sender_id !== $user->id) {
120
                $msg->readed = true;
121
                $msg->save();
122
            }
123
        }
124
125
        return json_encode([
126
            'status' => 1,
127
            'data' => array_reverse($response),
128
            'blocked' => !Blacklist::check($user->id, $corId)
129
        ]);
130
    }
131
}
132