Completed
Push — 2.0 ( e69d85...2b1775 )
by Kévin
19s
created

SerializerContextBuilder   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 4
dl 0
loc 39
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B createFromRequest() 0 26 6
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[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 ApiPlatform\Core\Serializer;
15
16
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
17
use ApiPlatform\Core\Util\RequestAttributesExtractor;
18
use Symfony\Component\HttpFoundation\Request;
19
20
/**
21
 * {@inheritdoc}
22
 *
23
 * @author Kévin Dunglas <[email protected]>
24
 */
25
final class SerializerContextBuilder implements SerializerContextBuilderInterface
26
{
27
    private $resourceMetadataFactory;
28
29
    public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory)
30
    {
31
        $this->resourceMetadataFactory = $resourceMetadataFactory;
32
    }
33
34
    /**
35
     * {@inheritdoc}
36
     */
37
    public function createFromRequest(Request $request, bool $normalization, array $attributes = null): array
38
    {
39
        if (null === $attributes) {
40
            $attributes = RequestAttributesExtractor::extractAttributes($request);
41
        }
42
43
        $resourceMetadata = $this->resourceMetadataFactory->create($attributes['resource_class']);
44
        $key = $normalization ? 'normalization_context' : 'denormalization_context';
45
46
        if (isset($attributes['collection_operation_name'])) {
47
            $context = $resourceMetadata->getCollectionOperationAttribute($attributes['collection_operation_name'], $key, [], true);
48
            $context['collection_operation_name'] = $attributes['collection_operation_name'];
49
        } else {
50
            $context = $resourceMetadata->getItemOperationAttribute($attributes['item_operation_name'], $key, [], true);
51
            $context['item_operation_name'] = $attributes['item_operation_name'];
52
        }
53
54
        if (!$normalization && !isset($context['api_allow_update'])) {
55
            $context['api_allow_update'] = Request::METHOD_PUT === $request->getMethod();
56
        }
57
58
        $context['resource_class'] = $attributes['resource_class'];
59
        $context['request_uri'] = $request->getRequestUri();
60
61
        return $context;
62
    }
63
}
64