Completed
Push — master ( 572f95...1f2c43 )
by Valentyn
03:47
created

BaseController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php
2
declare(strict_types=1);
3
4
namespace App\Controller;
5
6
use App\Translation\TranslatedResponseTrait;
7
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
8
use Symfony\Component\HttpFoundation\JsonResponse;
9
10
/**
11
 * Class BaseController
12
 * @package App\Controller
13
 */
14
abstract class BaseController extends Controller implements ControllerInterface
15
{
16
    use TranslatedResponseTrait;
17
18
    /**
19
     * @param $data
20
     * @param int $status
21
     * @param array $headers
22
     * @param array $context
23
     * @return JsonResponse
24
     */
25 15
    protected function response($data, int $status = 200, array $headers = [], array $context = []): JsonResponse
26
    {
27 15
        $contextWithRoles = $this->appendRolesToContextGroups($context);
28 15
        $translatedContent = $this->translateResponse($data, $contextWithRoles);
29
30 15
        return $this->json($translatedContent, $status, $headers, $context);
31
    }
32
33 15
    private function appendRolesToContextGroups(?array $context): array
34
    {
35 15
        if ($this->getUser() === null) return $context;
36
37 5
        if ($context === null) {
38
            return [
39
                'groups' => $this->getUser()->getRoles(),
40
            ];
41
        }
42
43 5
        if (isset($context['groups'])) {
44 5
            $context['groups'] = array_merge($context['groups'], $this->getUser()->getRoles());
45
        } else {
46
            $context['groups'] = $this->getUser()->getRoles();
47
        }
48
49 5
        return $context;
50
    }
51
}