Completed
Pull Request — 2.0 (#996)
by
unknown
02:54
created

SerializerContextBuilder::createFromRequest()   C

Complexity

Conditions 7
Paths 9

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 16
nc 9
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\Exception\RuntimeException;
15
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
16
use ApiPlatform\Core\Util\RequestAttributesExtractor;
17
use Symfony\Component\HttpFoundation\Request;
18
19
/**
20
 * {@inheritdoc}
21
 *
22
 * @author Kévin Dunglas <[email protected]>
23
 */
24
final class SerializerContextBuilder implements SerializerContextBuilderInterface
25
{
26
    private $resourceMetadataFactory;
27
28
    public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory)
29
    {
30
        $this->resourceMetadataFactory = $resourceMetadataFactory;
31
    }
32
33
    /**
34
     * {@inheritdoc}
35
     */
36
    public function createFromRequest(Request $request, bool $normalization, array $attributes = null): array
37
    {
38
        if (null === $attributes && !$attributes = RequestAttributesExtractor::extractAttributes($request)) {
39
            throw new RuntimeException('Request attributes are not valid.');
40
        }
41
42
        $resourceMetadata = $this->resourceMetadataFactory->create($attributes['resource_class']);
43
        $key = $normalization ? 'normalization_context' : 'denormalization_context';
44
45
        if (isset($attributes['collection_operation_name'])) {
46
            $context = $resourceMetadata->getCollectionOperationAttribute($attributes['collection_operation_name'], $key, [], true);
47
            $context['collection_operation_name'] = $attributes['collection_operation_name'];
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
60
        return $context;
61
    }
62
}
63