Passed
Pull Request — master (#2384)
by
unknown
04:45
created

DocAction::getPathAndMethod()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 11
rs 10
c 0
b 0
f 0
cc 4
nc 4
nop 1
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\Bridge\Symfony\Bundle\Action;
15
16
use ApiPlatform\Core\Api\FormatsProviderInterface;
17
use ApiPlatform\Core\Bridge\Symfony\Bundle\EventListener\DocListener;
18
use ApiPlatform\Core\Documentation\Documentation;
19
use ApiPlatform\Core\Exception\InvalidArgumentException;
20
use ApiPlatform\Core\Exception\RuntimeException;
21
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
22
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
23
use ApiPlatform\Core\Util\RequestAttributesExtractor;
24
use Symfony\Component\HttpFoundation\RedirectResponse;
25
use Symfony\Component\HttpFoundation\Request;
26
use Symfony\Component\HttpFoundation\Response;
27
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
28
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
29
30
/**
31
 * Displays the documentation.
32
 *
33
 * @author Kévin Dunglas <[email protected]>
34
 */
35
final class DocAction
36
{
37
    private $resourceNameCollectionFactory;
38
    private $resourceMetadataFactory;
39
    private $normalizer;
40
    private $twig;
41
    private $urlGenerator;
42
    private $title;
43
    private $description;
44
    private $version;
45
    private $showWebby;
46
    private $formats = [];
47
    private $oauthEnabled;
48
    private $oauthClientId;
49
    private $oauthClientSecret;
50
    private $oauthType;
51
    private $oauthFlow;
52
    private $oauthTokenUrl;
53
    private $oauthAuthorizationUrl;
54
    private $oauthScopes;
55
    private $formatsProvider;
56
57
    /**
58
     * @throws InvalidArgumentException
59
     */
60
    public function __construct(ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, NormalizerInterface $normalizer, \Twig_Environment $twig, UrlGeneratorInterface $urlGenerator, string $title = '', string $description = '', string $version = '', /* FormatsProviderInterface */ $formatsProvider = [], $oauthEnabled = false, $oauthClientId = '', $oauthClientSecret = '', $oauthType = '', $oauthFlow = '', $oauthTokenUrl = '', $oauthAuthorizationUrl = '', $oauthScopes = [], bool $showWebby = true)
61
    {
62
        $this->resourceNameCollectionFactory = $resourceNameCollectionFactory;
63
        $this->resourceMetadataFactory = $resourceMetadataFactory;
64
        $this->normalizer = $normalizer;
65
        $this->twig = $twig;
66
        $this->urlGenerator = $urlGenerator;
67
        $this->title = $title;
68
        $this->showWebby = $showWebby;
69
        $this->description = $description;
70
        $this->version = $version;
71
        $this->oauthEnabled = $oauthEnabled;
72
        $this->oauthClientId = $oauthClientId;
73
        $this->oauthClientSecret = $oauthClientSecret;
74
        $this->oauthType = $oauthType;
75
        $this->oauthFlow = $oauthFlow;
76
        $this->oauthTokenUrl = $oauthTokenUrl;
77
        $this->oauthAuthorizationUrl = $oauthAuthorizationUrl;
78
        $this->oauthScopes = $oauthScopes;
79
80
        if (\is_array($formatsProvider)) {
81
            if ($formatsProvider) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $formatsProvider of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
82
                // Only trigger notification for non-default argument
83
                @trigger_error('Using an array as formats provider is deprecated since API Platform 2.3 and will not be possible anymore in API Platform 3', E_USER_DEPRECATED);
84
            }
85
            $this->formats = $formatsProvider;
86
87
            return;
88
        }
89
        if (!$formatsProvider instanceof FormatsProviderInterface) {
90
            throw new InvalidArgumentException(sprintf('The "$formatsProvider" argument is expected to be an implementation of the "%s" interface.', FormatsProviderInterface::class));
91
        }
92
93
        $this->formatsProvider = $formatsProvider;
94
    }
95
96
    public function __invoke(Request $request)
97
    {
98
        // BC check to be removed in 3.0
99
        if (null !== $this->formatsProvider) {
100
            $this->formats = $this->formatsProvider->getFormatsFromAttributes(RequestAttributesExtractor::extractAttributes($request));
101
        }
102
103
        $documentation = new Documentation($this->resourceNameCollectionFactory->create(), $this->title, $this->description, $this->version, $this->formats);
104
105
        if (DocListener::GRAPHQL === $request->get('ui')) {
106
            return new RedirectResponse($this->urlGenerator->generate(DocListener::CONTROLLER_GRAPHQL));
107
        }
108
109
        return new Response($this->twig->render(
110
            DocListener::RE_DOC === $request->get('ui') ? '@ApiPlatform/Redoc/index.html.twig' : '@ApiPlatform/SwaggerUi/index.html.twig',
111
            $this->getContext($request, $documentation)
112
        ));
113
    }
114
115
    /**
116
     * Gets the base Twig context.
117
     */
118
    private function getContext(Request $request, Documentation $documentation): array
119
    {
120
        $context = [
121
            'title' => $this->title,
122
            'description' => $this->description,
123
            'formats' => $this->formats,
124
            'showWebby' => $this->showWebby,
125
        ];
126
127
        $swaggerData = [
128
            'url' => $this->urlGenerator->generate('api_doc', ['format' => 'json']),
129
            'spec' => $this->normalizer->normalize($documentation, 'json', ['base_url' => $request->getBaseUrl(), 'spec_version' => $request->query->getInt('spec_version', 3)]),
130
        ];
131
132
        $swaggerData['oauth'] = [
133
            'enabled' => $this->oauthEnabled,
134
            'clientId' => $this->oauthClientId,
135
            'clientSecret' => $this->oauthClientSecret,
136
            'type' => $this->oauthType,
137
            'flow' => $this->oauthFlow,
138
            'tokenUrl' => $this->oauthTokenUrl,
139
            'authorizationUrl' => $this->oauthAuthorizationUrl,
140
            'scopes' => $this->oauthScopes,
141
        ];
142
143
        if ($request->isMethodSafe(false) && null !== $resourceClass = $request->attributes->get('_api_resource_class')) {
144
            $swaggerData['id'] = $request->attributes->get('id');
145
            $swaggerData['queryParameters'] = $request->query->all();
146
147
            $metadata = $this->resourceMetadataFactory->create($resourceClass);
148
            $swaggerData['shortName'] = $metadata->getShortName();
149
150
            if (null !== $collectionOperationName = $request->attributes->get('_api_collection_operation_name')) {
151
                $swaggerData['operationId'] = sprintf('%s%sCollection', $collectionOperationName, $swaggerData['shortName']);
152
            } elseif (null !== $itemOperationName = $request->attributes->get('_api_item_operation_name')) {
153
                $swaggerData['operationId'] = sprintf('%s%sItem', $itemOperationName, $swaggerData['shortName']);
154
            } elseif (null !== $subresourceOperationContext = $request->attributes->get('_api_subresource_context')) {
155
                $swaggerData['operationId'] = $subresourceOperationContext['operationId'];
156
            }
157
158
            list($swaggerData['path'], $swaggerData['method']) = $this->getPathAndMethod($swaggerData);
159
        }
160
161
        return $context + ['swagger_data' => $swaggerData];
162
    }
163
164
    private function getPathAndMethod(array $swaggerData): array
165
    {
166
        foreach ($swaggerData['spec']['paths'] as $path => $operations) {
167
            foreach ($operations as $method => $operation) {
168
                if ($operation['operationId'] === $swaggerData['operationId']) {
169
                    return [$path, $method];
170
                }
171
            }
172
        }
173
174
        throw new RuntimeException(sprintf('The operation "%s" cannot be found in the Swagger specification.', $swaggerData['operationId']));
175
    }
176
}
177