Completed
Push — master ( 1302da...3a2ccf )
by Valentyn
03:07
created

BaseController   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 89.47%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 3
dl 0
loc 54
ccs 17
cts 19
cp 0.8947
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A response() 0 11 2
A addMetaPaginationInfo() 0 11 1
A appendRolesToContextGroups() 0 18 4
1
<?php
2
declare(strict_types=1);
3
4
namespace App\Controller;
5
6
use App\Pagination\PaginatedCollectionInterface;
7
use App\Translation\TranslatedResponseTrait;
8
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
9
use Symfony\Component\HttpFoundation\JsonResponse;
10
11
/**
12
 * Class BaseController
13
 * @package App\Controller
14
 */
15
abstract class BaseController extends Controller implements ControllerInterface
16
{
17
    use TranslatedResponseTrait;
18
19
    /**
20
     * @param $data
21
     * @param int $status
22
     * @param array $headers
23
     * @param array $context
24
     * @return JsonResponse
25
     */
26 18
    protected function response($data, int $status = 200, array $headers = [], array $context = []): JsonResponse
27
    {
28 18
        if ($data instanceof PaginatedCollectionInterface) {
29 5
            $data = $this->addMetaPaginationInfo($data);
30
        }
31
32 18
        $contextWithRoles = $this->appendRolesToContextGroups($context);
33 18
        $translatedContent = $this->translateResponse($data, $contextWithRoles);
34
35 18
        return $this->json($translatedContent, $status, $headers, $context);
36
    }
37
38 5
    private function addMetaPaginationInfo(PaginatedCollectionInterface $paginatedCollection)
39
    {
40
        return [
41 5
            'data' => $paginatedCollection->getItems(),
42
            'paging' => [
43 5
                'total' => $paginatedCollection->getTotal(),
44 5
                'offset' => $paginatedCollection->getOffset(),
45 5
                'limit' => $paginatedCollection->getLimit(),
46
            ]
47
        ];
48
    }
49
50 18
    private function appendRolesToContextGroups(?array $context): array
51
    {
52 18
        if ($this->getUser() === null) return $context;
53
54 5
        if ($context === null) {
55
            return [
56
                'groups' => $this->getUser()->getRoles(),
57
            ];
58
        }
59
60 5
        if (isset($context['groups'])) {
61 5
            $context['groups'] = array_merge($context['groups'], $this->getUser()->getRoles());
62
        } else {
63
            $context['groups'] = $this->getUser()->getRoles();
64
        }
65
66 5
        return $context;
67
    }
68
}