Passed
Push — develop ( ef53f3...80bc53 )
by BENARD
08:34
created

TopicContextBuilder::createFromRequest()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 19
rs 9.6111
cc 5
nc 3
nop 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace ProjetNormandie\ForumBundle\Serializer;
6
7
use ApiPlatform\State\SerializerContextBuilderInterface;
8
use ProjetNormandie\ForumBundle\Entity\Category;
9
use ProjetNormandie\ForumBundle\Entity\Forum;
10
use ProjetNormandie\ForumBundle\Entity\Topic;
11
use Symfony\Component\HttpFoundation\Request;
12
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
13
14
final class TopicContextBuilder implements SerializerContextBuilderInterface
15
{
16
    private SerializerContextBuilderInterface $decorated;
17
    private AuthorizationCheckerInterface $authorizationChecker;
18
19
    public function __construct(
20
        SerializerContextBuilderInterface $decorated,
21
        AuthorizationCheckerInterface $authorizationChecker
22
    ) {
23
        $this->decorated = $decorated;
24
        $this->authorizationChecker = $authorizationChecker;
25
    }
26
27
    public function createFromRequest(Request $request, bool $normalization, ?array $extractedAttributes = null): array
28
    {
29
        $context = $this->decorated->createFromRequest($request, $normalization, $extractedAttributes);
30
        $resourceClass = $context['resource_class'] ?? null;
31
32
        if (
33
            $resourceClass === Topic::class
34
            && isset($context['groups'])
35
            && true === $normalization
36
        ) {
37
            $baseGroups = $context['groups'];
38
39
            if ($this->authorizationChecker->isGranted('ROLE_USER')) {
40
                $baseGroups[] = 'topic:read-status';
41
            }
42
43
            $context['groups'] = array_unique($baseGroups);
44
        }
45
        return $context;
46
    }
47
}
48