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
|
|
|
} |