Completed
Pull Request — master (#904)
by Antoine
03:00
created

SerializerContextBuilder::createFromRequest()   C

Complexity

Conditions 7
Paths 16

Size

Total Lines 29
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 29
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 19
nc 16
nop 3
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
namespace ApiPlatform\Core\Serializer;
13
14
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
15
use ApiPlatform\Core\Util\RequestAttributesExtractor;
16
use Symfony\Component\HttpFoundation\Request;
17
18
/**
19
 * {@inheritdoc}
20
 *
21
 * @author Kévin Dunglas <[email protected]>
22
 */
23
final class SerializerContextBuilder implements SerializerContextBuilderInterface
24
{
25
    private $resourceMetadataFactory;
26
27
    public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory)
28
    {
29
        $this->resourceMetadataFactory = $resourceMetadataFactory;
30
    }
31
32
    /**
33
     * {@inheritdoc}
34
     */
35
    public function createFromRequest(Request $request, bool $normalization, array $attributes = null): array
36
    {
37
        if (null === $attributes) {
38
            $attributes = RequestAttributesExtractor::extractAttributes($request);
39
        }
40
41
        $resourceMetadata = $this->resourceMetadataFactory->create($attributes['resource_class']);
42
        $key = $normalization ? 'normalization_context' : 'denormalization_context';
43
44
        if (isset($attributes['collection_operation_name']) || isset($attributes['subcollection_operation_name'])) {
45
            $attribute = $attributes['collection_operation_name'] ?? $attributes['subcollection_operation_name'];
46
            $context = $resourceMetadata->getCollectionOperationAttribute($attribute, $key, [], true);
47
            $context['collection_operation_name'] = $attribute;
48
        } else {
49
            $context = $resourceMetadata->getItemOperationAttribute($attributes['item_operation_name'], $key, [], true);
50
            $context['item_operation_name'] = $attributes['item_operation_name'];
51
        }
52
53
        if (!$normalization && !isset($context['api_allow_update'])) {
54
            $context['api_allow_update'] = Request::METHOD_PUT === $request->getMethod();
55
        }
56
57
        $context['resource_class'] = $attributes['resource_class'];
58
        $context['request_uri'] = $request->getRequestUri();
59
        $context['subcollection_property'] = $attributes['subcollection_property'] ?? null;
60
        $context['subcollection_resource_class'] = $attributes['subcollection_resource_class'] ?? null;
61
62
        return $context;
63
    }
64
}
65