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

BaseController::appendRolesToContextGroups()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4.25

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 6
cts 8
cp 0.75
rs 9.2
c 0
b 0
f 0
cc 4
eloc 10
nc 4
nop 1
crap 4.25
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
}