Completed
Pull Request — master (#590)
by Kévin
04:30
created

SerializerContextBuilder::createFromRequest()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 24
rs 8.6845
cc 4
eloc 15
nc 8
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\Api\RequestAttributesExtractor;
15
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
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 $extractedAttributes = null) : array
36
    {
37
        if (null === $extractedAttributes) {
38
            $extractedAttributes = RequestAttributesExtractor::extractAttributes($request);
39
        }
40
41
        list($resourceClass, $collectionOperationName, $itemOperationName) = $extractedAttributes;
42
43
        $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
44
        $key = $normalization ? 'normalization_context' : 'denormalization_context';
45
46
        if ($collectionOperationName) {
47
            $context = $resourceMetadata->getCollectionOperationAttribute($collectionOperationName, $key, [], true);
48
            $context['collection_operation_name'] = $collectionOperationName;
49
        } else {
50
            $context = $resourceMetadata->getItemOperationAttribute($itemOperationName, $key, [], true);
51
            $context['item_operation_name'] = $itemOperationName;
52
        }
53
54
        $context['resource_class'] = $resourceClass;
55
        $context['request_uri'] = $request->getRequestUri();
56
57
        return $context;
58
    }
59
}
60