Passed
Push — master ( 81f334...c86e8c )
by Mihail
03:35
created

ActionCount   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
dl 0
loc 35
rs 10
c 0
b 0
f 0
wmc 5
lcom 1
cbo 5

1 Method

Rating   Name   Duplication   Size   Complexity  
B cnt() 0 26 5
1
<?php
2
3
namespace Apps\Controller\Api\Comments;
4
5
use Apps\ActiveRecord\CommentPost;
6
use Ffcms\Core\Exception\NativeException;
7
use Ffcms\Core\Helper\Type\Any;
8
use Ffcms\Core\Network\Request;
9
use Ffcms\Core\Network\Response;
10
use Apps\ActiveRecord\App as AppRecord;
11
12
/**
13
 * Trait ActionCount
14
 * @package Apps\Controller\Api\Comments
15
 * @property Request $request
16
 * @property Response $response
17
 * @method void setJsonHeader()
18
 */
19
trait ActionCount
20
{
21
    /**
22
     * Get commentaries count for pathway. Pathway should be array [itemId => pathway]
23
     * @return string
24
     * @throws NativeException
25
     * @throws \Ffcms\Core\Exception\SyntaxException
26
     */
27
    public function cnt(): ?string
28
    {
29
        // set headers
30
        $this->setJsonHeader();
31
        // get configs
32
        $configs = AppRecord::getConfigs('widget', 'Comments');
33
        // get path array from request
34
        $path = $this->request->query->get('path');
35
        if (!Any::isArray($path) || count($path) < 1) {
36
            throw new NativeException('Wrong query params');
37
        }
38
39
        $count = [];
40
        // for each item in path array calculate comments count
41
        foreach ($path as $id => $uri) {
42
            $query = CommentPost::where('pathway', '=', $uri)->where('moderate', '=', 0);
43
            // check if comments is depend of language locale
44
            if ((int)$configs['onlyLocale'] === 1) {
45
                $query = $query->where('lang', '=', $this->request->getLanguage());
46
            }
47
            // set itemId => count
48
            $count[(int)$id] = $query->count();
49
        }
50
        // render json response
51
        return json_encode(['status' => 1, 'count' => $count]);
52
    }
53
}
54