Completed
Pull Request — 2.0 (#1065)
by Pierre
04:11
created

SerializerContextBuilder   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

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

2 Methods

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