Completed
Push — master ( 1a9043...984777 )
by Valentyn
08:31
created

BaseController   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 57.89%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 3
dl 0
loc 54
ccs 11
cts 19
cp 0.5789
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\PaginatedCollection;
7
use App\Pagination\PaginatorBuilder;
8
use App\Translation\TranslatedResponseTrait;
9
use Doctrine\ORM\Tools\Pagination\Paginator;
10
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
11
use Symfony\Component\HttpFoundation\JsonResponse;
12
13
/**
14
 * Class BaseController
15
 * @package App\Controller
16
 */
17
abstract class BaseController extends Controller implements ControllerInterface
18
{
19
    use TranslatedResponseTrait;
20
21
    /**
22
     * @param $data
23
     * @param int $status
24
     * @param array $headers
25
     * @param array $context
26
     * @return JsonResponse
27
     */
28 18
    protected function response($data, int $status = 200, array $headers = [], array $context = []): JsonResponse
29
    {
30 18
        if ($data instanceof PaginatedCollection) {
31
            $data = $this->addMetaPaginationInfo($data);
32
        }
33
34 18
        $contextWithRoles = $this->appendRolesToContextGroups($context);
35 18
        $translatedContent = $this->translateResponse($data, $contextWithRoles);
36
37 18
        return $this->json($translatedContent, $status, $headers, $context);
38
    }
39
40
    private function addMetaPaginationInfo(PaginatedCollection $paginatedCollection)
41
    {
42
        return [
43
            'data' => $paginatedCollection->getItems(),
44
            'paging' => [
45
                'total' => $paginatedCollection->getTotal(),
46
                'offset' => $paginatedCollection->getOffset(),
47
                'limit' => $paginatedCollection->getLimit(),
48
            ]
49
        ];
50
    }
51
52 18
    private function appendRolesToContextGroups(?array $context): array
53
    {
54 18
        if ($this->getUser() === null) return $context;
55
56 5
        if ($context === null) {
57
            return [
58
                'groups' => $this->getUser()->getRoles(),
59
            ];
60
        }
61
62 5
        if (isset($context['groups'])) {
63 5
            $context['groups'] = array_merge($context['groups'], $this->getUser()->getRoles());
64
        } else {
65
            $context['groups'] = $this->getUser()->getRoles();
66
        }
67
68 5
        return $context;
69
    }
70
}