Passed
Pull Request — master (#3367)
by Alan
04:18
created

ContextTrait::getOperationNameFromContext()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 10
nc 8
nop 1
dl 0
loc 16
rs 9.6111
c 0
b 0
f 0
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 Symfony\Component\HttpFoundation\Request;
17
18
/**
19
 * Creates and manipulates the Serializer context.
20
 *
21
 * @internal
22
 *
23
 * @author Kévin Dunglas <[email protected]>
24
 * @author Alan Poulain <[email protected]>
25
 */
26
trait ContextTrait
27
{
28
    /**
29
     * Initializes the context.
30
     */
31
    private function initContext(string $resourceClass, array $context): array
32
    {
33
        return array_merge($context, [
34
            'api_sub_level' => true,
35
            'resource_class' => $resourceClass,
36
        ]);
37
    }
38
39
    private function addRequestContext(Request $request, array $context): array
40
    {
41
        return array_merge($context, [
42
            'request_query' => $request->query->all(),
43
            'request_attributes' => $request->attributes->all(),
44
            'request_method' => $request->getMethod(),
45
            'request_content_type' => $request->getContentType(),
46
            'request_request_uri' => $request->getRequestUri(),
47
            'request_uri' => $request->getUri(),
48
        ]);
49
    }
50
51
    private function getOperationNameFromContext(array $context): string
52
    {
53
        $operationName = $context['subresource_operation_name'] ?? null;
54
        if (isset($context['collection_operation_name'])) {
55
            $operationName = $context['collection_operation_name'];
56
        } elseif (isset($context['item_operation_name'])) {
57
            $operationName = $context['item_operation_name'];
58
        } elseif (isset($context['resource_operation_name'])) {
59
            $operationName = $context['resource_operation_name'];
60
        }
61
62
        if (!\is_string($operationName)) {
63
            throw new \RuntimeException('Operation name cannot be extracted');
64
        }
65
66
        return $operationName;
67
    }
68
}
69