ActionList::aList()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 50
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 25
nc 4
nop 2
dl 0
loc 50
rs 9.52
c 0
b 0
f 0
1
<?php
2
3
namespace Apps\Controller\Api\Comments;
4
5
use Apps\ActiveRecord\App as AppRecord;
6
use Apps\ActiveRecord\CommentPost;
7
use Apps\Model\Api\Comments\EntityCommentData;
8
use Ffcms\Core\Exception\NotFoundException;
9
use Ffcms\Core\Network\Request;
10
use Ffcms\Core\Network\Response;
11
12
/**
13
 * Trait ActionList
14
 * @package Apps\Controller\Api\Comments
15
 * @property Request $request
16
 * @property Response $response
17
 * @method void setJsonHeader()
18
 */
19
trait ActionList
20
{
21
    /**
22
     * List comments as json object with defined offset index
23
     * @param string $appName
24
     * @param string $appId
25
     * @return string
26
     * @throws NotFoundException
27
     */
28
    public function aList(string $appName, string $appId): ?string
29
    {
30
        // set header
31
        $this->setJsonHeader();
32
        // get configs
33
        $configs = AppRecord::getConfigs('widget', 'Comments');
34
        // items per page
35
        $perPage = (int)$configs['perPage'];
36
        // offset can be only integer
37
        $index = (int)$this->request->query->get('offset', 0);
38
        $offset = $perPage * $index;
39
40
        // select comments from db and check it
41
        $query = CommentPost::where('app_name', $appName)
42
            ->where('app_relation_id', $appId)
43
            ->where('moderate', false);
44
45
        // check if comments is depend of language locale
46
        if ((bool)$configs['onlyLocale']) {
47
            $query = $query->where('lang', $this->request->getLanguage());
48
        }
49
50
        // calculate total comment count
51
        $count = $query->count();
52
53
        // get comments with offset and limit
54
        $records = $query->with(['user', 'user.profile', 'user.role'])
55
            ->skip($offset)
56
            ->take($perPage)
57
            ->get();
58
59
        // check if records is not empty
60
        if ($records->count() < 1) {
61
            throw new NotFoundException(__('There is no comments found yet. You can be the first!'));
62
        }
63
64
        // build output json data as array
65
        $data = [];
66
        $records->each(function ($comment) use (&$data){
67
            $data[] = (new EntityCommentData($comment))->make();
68
        });
69
70
        // reduce count to current offset
71
        $count -= $offset + $perPage;
72
73
        // render output json
74
        return json_encode([
75
            'status' => 1,
76
            'data' => $data,
77
            'leftCount' => $count < 0 ? 0 : $count
78
        ]);
79
    }
80
}
81