ActionShowAnswer::showAnswers()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 33
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 17
nc 5
nop 1
dl 0
loc 33
rs 9.3888
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\CommentAnswer;
7
use Apps\Model\Api\Comments\EntityCommentData;
8
use Ffcms\Core\Exception\ForbiddenException;
9
use Ffcms\Core\Exception\NotFoundException;
10
use Ffcms\Core\Helper\Type\Any;
11
use Ffcms\Core\Network\Request;
12
use Ffcms\Core\Network\Response;
13
14
/**
15
 * Trait ActionShowAnswer
16
 * @package Apps\Controller\Api\Comments
17
 * @property Request $request
18
 * @property Response $response
19
 * @method void setJsonHeader()
20
 */
21
trait ActionShowAnswer
22
{
23
    /**
24
     * List answers by comment id as json object
25
     * @param string $commentId
26
     * @return string
27
     * @throws ForbiddenException
28
     * @throws NotFoundException
29
     */
30
    public function showAnswers(string $commentId): ?string
31
    {
32
        $this->setJsonHeader();
33
        // check input data
34
        if (!Any::isInt($commentId) || $commentId < 1) {
35
            throw new ForbiddenException('Input data is incorrect');
36
        }
37
38
        // get configs
39
        $configs = AppRecord::getConfigs('widget', 'Comments');
40
41
        // get data from db by comment id
42
        $records = CommentAnswer::with(['user', 'user.profile', 'user.role'])
43
            ->where('comment_id', $commentId)
44
            ->where('moderate', false);
45
        if ((bool)$configs['onlyLocale']) {
46
            $records = $records->where('lang', $this->request->getLanguage());
47
        }
48
49
        // check objects count
50
        if ($records->count() < 1) {
51
            throw new NotFoundException(__('No answers for comment is founded'));
52
        }
53
54
        // prepare output
55
        $response = [];
56
        $records->get()->each(function($item) use (&$response){
57
            $response[] = (new EntityCommentData($item))->make();
58
        });
59
60
        return json_encode([
61
            'status' => 1,
62
            'data' => $response
63
        ]);
64
    }
65
}
66