SerializeFormatResolver   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 27
ccs 11
cts 11
cp 1
rs 10
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getFormat() 0 8 2
A getFormatFromRequest() 0 6 4
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Components Bundle Project
5
 *
6
 * (c) Daniel West <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Silverback\ApiComponentsBundle\Serializer;
15
16
use Symfony\Component\HttpFoundation\Request;
17
use Symfony\Component\HttpFoundation\RequestStack;
18
19
/**
20
 * @author Daniel West <[email protected]>
21
 */
22
final class SerializeFormatResolver implements SerializeFormatResolverInterface
23
{
24
    private RequestStack $requestStack;
25
    private string $defaultFormat;
26
27 6
    public function __construct(RequestStack $requestStack, string $defaultFormat = 'jsonld')
28
    {
29 6
        $this->requestStack = $requestStack;
30 6
        $this->defaultFormat = $defaultFormat;
31
    }
32
33 2
    public function getFormat(): string
34
    {
35 2
        $request = $this->requestStack->getMainRequest();
36 2
        if (!$request) {
37 1
            return $this->defaultFormat;
38
        }
39
40 1
        return $this->getFormatFromRequest($request);
41
    }
42
43 5
    public function getFormatFromRequest(Request $request): string
44
    {
45
        // Symfony 6.2 deprecated getContentType in favor of getContentTypeFormat
46 5
        $contentTypeMethod = method_exists($request, 'getContentTypeFormat') ? 'getContentTypeFormat' : 'getContentType';
47
48 5
        return $request->getRequestFormat(null) ?: $request->{$contentTypeMethod}() ?: $this->defaultFormat;
49
    }
50
}
51