Passed
Pull Request — master (#2748)
by Han Hui
05:09
created

Configuration::addDoctrineMongoDbOdmSection()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 8
rs 10
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\Bridge\Symfony\Bundle\DependencyInjection;
15
16
use ApiPlatform\Core\Bridge\Elasticsearch\Metadata\Document\DocumentMetadata;
17
use ApiPlatform\Core\Exception\FilterValidationException;
18
use ApiPlatform\Core\Exception\InvalidArgumentException;
19
use Doctrine\Bundle\DoctrineBundle\DoctrineBundle;
20
use Doctrine\Bundle\MongoDBBundle\DoctrineMongoDBBundle;
21
use Doctrine\ORM\OptimisticLockException;
22
use Doctrine\ORM\Version as DoctrineOrmVersion;
23
use Elasticsearch\Client as ElasticsearchClient;
24
use FOS\UserBundle\FOSUserBundle;
25
use GraphQL\GraphQL;
26
use Symfony\Bundle\FullStack;
0 ignored issues
show
Bug introduced by
The type Symfony\Bundle\FullStack was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
27
use Symfony\Bundle\MercureBundle\MercureBundle;
28
use Symfony\Bundle\TwigBundle\TwigBundle;
29
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
30
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
31
use Symfony\Component\Config\Definition\ConfigurationInterface;
32
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
33
use Symfony\Component\HttpFoundation\Response;
34
use Symfony\Component\Messenger\MessageBusInterface;
35
use Symfony\Component\Serializer\Exception\ExceptionInterface;
36
37
/**
38
 * The configuration of the bundle.
39
 *
40
 * @author Kévin Dunglas <[email protected]>
41
 * @author Baptiste Meyer <[email protected]>
42
 */
43
final class Configuration implements ConfigurationInterface
44
{
45
    /**
46
     * {@inheritdoc}
47
     */
48
    public function getConfigTreeBuilder()
49
    {
50
        if (method_exists(TreeBuilder::class, 'getRootNode')) {
51
            $treeBuilder = new TreeBuilder('api_platform');
52
            $rootNode = $treeBuilder->getRootNode();
53
        } else {
54
            $treeBuilder = new TreeBuilder();
55
            $rootNode = $treeBuilder->root('api_platform');
56
        }
57
58
        $rootNode
59
            ->children()
60
                ->scalarNode('title')
61
                    ->info('The title of the API.')
62
                    ->cannotBeEmpty()
63
                    ->defaultValue('')
64
                ->end()
65
                ->scalarNode('description')
66
                    ->info('The description of the API.')
67
                    ->cannotBeEmpty()
68
                    ->defaultValue('')
69
                ->end()
70
                ->scalarNode('version')
71
                    ->info('The version of the API.')
72
                    ->cannotBeEmpty()
73
                    ->defaultValue('0.0.0')
74
                ->end()
75
                ->booleanNode('show_webby')->defaultTrue()->info('If true, show Webby on the documentation page')->end()
76
                ->scalarNode('default_operation_path_resolver')
77
                    ->defaultValue('api_platform.operation_path_resolver.underscore')
78
                    ->setDeprecated('The use of the `default_operation_path_resolver` has been deprecated in 2.1 and will be removed in 3.0. Use `path_segment_name_generator` instead.')
79
                    ->info('Specify the default operation path resolver to use for generating resources operations path.')
80
                ->end()
81
                ->scalarNode('name_converter')->defaultNull()->info('Specify a name converter to use.')->end()
82
                ->scalarNode('path_segment_name_generator')->defaultValue('api_platform.path_segment_name_generator.underscore')->info('Specify a path name generator to use.')->end()
83
                ->booleanNode('allow_plain_identifiers')->defaultFalse()->info('Allow plain identifiers, for example "id" instead of "@id" when denormalizing a relation.')->end()
84
                ->arrayNode('validator')
85
                    ->addDefaultsIfNotSet()
86
                    ->children()
87
                        ->variableNode('serialize_payload_fields')->defaultValue([])->info('Enable the serialization of payload fields when a validation error is thrown.')->end()
88
                    ->end()
89
                ->end()
90
                ->arrayNode('eager_loading')
91
                    ->canBeDisabled()
92
                    ->addDefaultsIfNotSet()
93
                    ->children()
94
                        ->booleanNode('fetch_partial')->defaultFalse()->info('Fetch only partial data according to serialization groups. If enabled, Doctrine ORM entities will not work as expected if any of the other fields are used.')->end()
95
                        ->integerNode('max_joins')->defaultValue(30)->info('Max number of joined relations before EagerLoading throws a RuntimeException')->end()
96
                        ->booleanNode('force_eager')->defaultTrue()->info('Force join on every relation. If disabled, it will only join relations having the EAGER fetch mode.')->end()
97
                    ->end()
98
                ->end()
99
                ->booleanNode('enable_fos_user')->defaultValue(class_exists(FOSUserBundle::class))->info('Enable the FOSUserBundle integration.')->end()
100
                ->booleanNode('enable_nelmio_api_doc')
101
                    ->defaultFalse()
102
                    ->setDeprecated('Enabling the NelmioApiDocBundle integration has been deprecated in 2.2 and will be removed in 3.0. NelmioApiDocBundle 3 has native support for API Platform.')
103
                    ->info('Enable the NelmioApiDocBundle integration.')
104
                ->end()
105
                ->booleanNode('enable_swagger')->defaultTrue()->info('Enable the Swagger documentation and export.')->end()
106
                ->booleanNode('enable_swagger_ui')->defaultValue(class_exists(TwigBundle::class))->info('Enable Swagger UI')->end()
107
                ->booleanNode('enable_re_doc')->defaultValue(class_exists(TwigBundle::class))->info('Enable ReDoc')->end()
108
                ->booleanNode('enable_entrypoint')->defaultTrue()->info('Enable the entrypoint')->end()
109
                ->booleanNode('enable_docs')->defaultTrue()->info('Enable the docs')->end()
110
                ->booleanNode('enable_profiler')->defaultTrue()->info('Enable the data collector and the WebProfilerBundle integration.')->end()
111
                ->arrayNode('collection')
112
                    ->addDefaultsIfNotSet()
113
                    ->children()
114
                        ->scalarNode('exists_parameter_name')->defaultValue('exists')->cannotBeEmpty()->info('The name of the query parameter to filter on nullable field values.')->end()
115
                        ->scalarNode('order')->defaultValue('ASC')->info('The default order of results.')->end() // Default ORDER is required for postgresql and mysql >= 5.7 when using LIMIT/OFFSET request
116
                        ->scalarNode('order_parameter_name')->defaultValue('order')->cannotBeEmpty()->info('The name of the query parameter to order results.')->end()
117
                        ->arrayNode('pagination')
118
                            ->canBeDisabled()
119
                            ->addDefaultsIfNotSet()
120
                            ->children()
121
                                ->booleanNode('enabled')->defaultTrue()->info('To enable or disable pagination for all resource collections by default.')->end()
122
                                ->booleanNode('partial')->defaultFalse()->info('To enable or disable partial pagination for all resource collections by default when pagination is enabled.')->end()
123
                                ->booleanNode('client_enabled')->defaultFalse()->info('To allow the client to enable or disable the pagination.')->end()
124
                                ->booleanNode('client_items_per_page')->defaultFalse()->info('To allow the client to set the number of items per page.')->end()
125
                                ->booleanNode('client_partial')->defaultFalse()->info('To allow the client to enable or disable partial pagination.')->end()
126
                                ->integerNode('items_per_page')->defaultValue(30)->info('The default number of items per page.')->end()
127
                                ->integerNode('maximum_items_per_page')->defaultNull()->info('The maximum number of items per page.')->end()
128
                                ->scalarNode('page_parameter_name')->defaultValue('page')->cannotBeEmpty()->info('The default name of the parameter handling the page number.')->end()
129
                                ->scalarNode('enabled_parameter_name')->defaultValue('pagination')->cannotBeEmpty()->info('The name of the query parameter to enable or disable pagination.')->end()
130
                                ->scalarNode('items_per_page_parameter_name')->defaultValue('itemsPerPage')->cannotBeEmpty()->info('The name of the query parameter to set the number of items per page.')->end()
131
                                ->scalarNode('partial_parameter_name')->defaultValue('partial')->cannotBeEmpty()->info('The name of the query parameter to enable or disable partial pagination.')->end()
132
                            ->end()
133
                        ->end()
134
                    ->end()
135
                ->end()
136
                ->arrayNode('mapping')
137
                    ->addDefaultsIfNotSet()
138
                    ->children()
139
                        ->arrayNode('paths')
140
                            ->prototype('scalar')->end()
141
                        ->end()
142
                    ->end()
143
                ->end()
144
                ->arrayNode('resource_class_directories')
145
                    ->prototype('scalar')->end()
146
                ->end()
147
            ->end();
148
149
        $this->addDoctrineOrmSection($rootNode);
150
        $this->addDoctrineMongoDbOdmSection($rootNode);
151
        $this->addOAuthSection($rootNode);
152
        $this->addGraphQlSection($rootNode);
153
        $this->addSwaggerSection($rootNode);
154
        $this->addHttpCacheSection($rootNode);
155
        $this->addMercureSection($rootNode);
156
        $this->addMessengerSection($rootNode);
157
        $this->addElasticsearchSection($rootNode);
158
159
        $this->addExceptionToStatusSection($rootNode);
160
161
        $this->addFormatSection($rootNode, 'formats', [
162
            'jsonld' => ['mime_types' => ['application/ld+json']],
163
            'json' => ['mime_types' => ['application/json']], // Swagger support
164
            'html' => ['mime_types' => ['text/html']], // Swagger UI support
165
        ]);
166
        $this->addFormatSection($rootNode, 'error_formats', [
167
            'jsonproblem' => ['mime_types' => ['application/problem+json']],
168
            'jsonld' => ['mime_types' => ['application/ld+json']],
169
        ]);
170
171
        return $treeBuilder;
172
    }
173
174
    private function addDoctrineOrmSection(ArrayNodeDefinition $rootNode): void
175
    {
176
        $rootNode
177
            ->children()
178
                ->arrayNode('doctrine')
179
                    ->{class_exists(DoctrineBundle::class) && class_exists(DoctrineOrmVersion::class) ? 'canBeDisabled' : 'canBeEnabled'}()
180
                ->end()
181
            ->end();
182
    }
183
184
    private function addDoctrineMongoDbOdmSection(ArrayNodeDefinition $rootNode): void
185
    {
186
        $rootNode
187
            ->children()
188
                ->arrayNode('doctrine_mongodb_odm')
189
                    ->{class_exists(DoctrineMongoDBBundle::class) ? 'canBeDisabled' : 'canBeEnabled'}()
190
                ->end()
191
            ->end();
192
    }
193
194
    private function addOAuthSection(ArrayNodeDefinition $rootNode): void
195
    {
196
        $rootNode
197
            ->children()
198
                ->arrayNode('oauth')
199
                    ->canBeEnabled()
200
                    ->addDefaultsIfNotSet()
201
                    ->children()
202
                        ->scalarNode('clientId')->defaultValue('')->info('The oauth client id.')->end()
203
                        ->scalarNode('clientSecret')->defaultValue('')->info('The oauth client secret.')->end()
0 ignored issues
show
Bug introduced by
The method scalarNode() does not exist on Symfony\Component\Config...der\NodeParentInterface. It seems like you code against a sub-type of Symfony\Component\Config...der\NodeParentInterface such as Symfony\Component\Config...ion\Builder\NodeBuilder. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

203
                        ->/** @scrutinizer ignore-call */ scalarNode('clientSecret')->defaultValue('')->info('The oauth client secret.')->end()
Loading history...
204
                        ->scalarNode('type')->defaultValue('oauth2')->info('The oauth client secret.')->end()
205
                        ->scalarNode('flow')->defaultValue('application')->info('The oauth flow grant type.')->end()
206
                        ->scalarNode('tokenUrl')->defaultValue('/oauth/v2/token')->info('The oauth token url.')->end()
207
                        ->scalarNode('authorizationUrl')->defaultValue('/oauth/v2/auth')->info('The oauth authentication url.')->end()
208
                        ->arrayNode('scopes')
209
                            ->prototype('scalar')->end()
210
                        ->end()
211
                    ->end()
212
                ->end()
213
            ->end();
214
    }
215
216
    private function addGraphQlSection(ArrayNodeDefinition $rootNode): void
217
    {
218
        $rootNode
219
            ->children()
220
                ->arrayNode('graphql')
221
                    ->{class_exists(GraphQL::class) ? 'canBeDisabled' : 'canBeEnabled'}()
222
                    ->addDefaultsIfNotSet()
223
                    ->children()
224
                        ->arrayNode('graphiql')
225
                            ->{class_exists(GraphQL::class) && class_exists(TwigBundle::class) ? 'canBeDisabled' : 'canBeEnabled'}()
226
                        ->end()
227
                    ->end()
228
                ->end()
229
            ->end();
230
    }
231
232
    private function addSwaggerSection(ArrayNodeDefinition $rootNode): void
233
    {
234
        $rootNode
235
            ->children()
236
                ->arrayNode('swagger')
237
                    ->addDefaultsIfNotSet()
238
                    ->children()
239
                             ->arrayNode('api_keys')
240
                                 ->prototype('array')
241
                                    ->children()
242
                                    ->scalarNode('name')
243
                                        ->info('The name of the header or query parameter containing the api key.')
244
                                    ->end()
245
                                    ->enumNode('type')
246
                                        ->info('Whether the api key should be a query parameter or a header.')
247
                                        ->values(['query', 'header'])
248
                                    ->end()
249
                                ->end()
250
                             ->end()
251
                        ->end()
252
                    ->end()
253
                ->end()
254
            ->end();
255
    }
256
257
    private function addHttpCacheSection(ArrayNodeDefinition $rootNode): void
258
    {
259
        $rootNode
260
            ->children()
261
                ->arrayNode('http_cache')
262
                    ->addDefaultsIfNotSet()
263
                    ->children()
264
                        ->booleanNode('etag')->defaultTrue()->info('Automatically generate etags for API responses.')->end()
265
                        ->integerNode('max_age')->defaultNull()->info('Default value for the response max age.')->end()
0 ignored issues
show
Bug introduced by
The method integerNode() does not exist on Symfony\Component\Config...der\NodeParentInterface. It seems like you code against a sub-type of Symfony\Component\Config...der\NodeParentInterface such as Symfony\Component\Config...ion\Builder\NodeBuilder. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

265
                        ->/** @scrutinizer ignore-call */ integerNode('max_age')->defaultNull()->info('Default value for the response max age.')->end()
Loading history...
266
                        ->integerNode('shared_max_age')->defaultNull()->info('Default value for the response shared (proxy) max age.')->end()
267
                        ->arrayNode('vary')
268
                            ->defaultValue(['Accept'])
269
                            ->prototype('scalar')->end()
270
                            ->info('Default values of the "Vary" HTTP header.')
271
                        ->end()
272
                        ->booleanNode('public')->defaultNull()->info('To make all responses public by default.')->end()
273
                        ->arrayNode('invalidation')
274
                            ->info('Enable the tags-based cache invalidation system.')
275
                            ->canBeEnabled()
276
                            ->children()
277
                                ->arrayNode('varnish_urls')
278
                                    ->defaultValue([])
279
                                    ->prototype('scalar')->end()
280
                                    ->info('URLs of the Varnish servers to purge using cache tags when a resource is updated.')
281
                                ->end()
282
                                ->variableNode('request_options')
283
                                    ->defaultValue([])
284
                                    ->validate()
285
                                        ->ifTrue(function ($v) { return false === \is_array($v); })
286
                                        ->thenInvalid('The request_options parameter must be an array.')
287
                                    ->end()
288
                                    ->info('To pass options to the client charged with the request.')
289
                                ->end()
290
                            ->end()
291
                        ->end()
292
                    ->end()
293
                ->end()
294
            ->end();
295
    }
296
297
    private function addMercureSection(ArrayNodeDefinition $rootNode): void
298
    {
299
        $rootNode
300
            ->children()
301
                ->arrayNode('mercure')
302
                    ->{class_exists(MercureBundle::class) ? 'canBeDisabled' : 'canBeEnabled'}()
303
                    ->children()
304
                        ->scalarNode('hub_url')
305
                            ->defaultNull()
306
                            ->info('The URL sent in the Link HTTP header. If not set, will default to the URL for MercureBundle\'s default hub.')
307
                        ->end()
308
                    ->end()
309
                ->end()
310
            ->end();
311
    }
312
313
    private function addMessengerSection(ArrayNodeDefinition $rootNode): void
314
    {
315
        $rootNode
316
            ->children()
317
                ->arrayNode('messenger')
318
                    ->{!class_exists(FullStack::class) && interface_exists(MessageBusInterface::class) ? 'canBeDisabled' : 'canBeEnabled'}()
319
                ->end()
320
            ->end();
321
    }
322
323
    private function addElasticsearchSection(ArrayNodeDefinition $rootNode): void
324
    {
325
        $rootNode
326
            ->children()
327
                ->arrayNode('elasticsearch')
328
                    ->canBeEnabled()
329
                    ->addDefaultsIfNotSet()
330
                    ->children()
331
                        ->booleanNode('enabled')
332
                            ->defaultFalse()
333
                            ->validate()
334
                                ->ifTrue()
335
                                ->then(static function (bool $v): bool {
336
                                    if (!class_exists(ElasticsearchClient::class)) {
337
                                        throw new InvalidConfigurationException('The elasticsearch/elasticsearch package is required for Elasticsearch support.');
338
                                    }
339
340
                                    return $v;
341
                                })
342
                            ->end()
343
                        ->end()
344
                        ->arrayNode('hosts')
0 ignored issues
show
Bug introduced by
The method arrayNode() does not exist on Symfony\Component\Config...der\NodeParentInterface. It seems like you code against a sub-type of Symfony\Component\Config...der\NodeParentInterface such as Symfony\Component\Config...ion\Builder\NodeBuilder. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

344
                        ->/** @scrutinizer ignore-call */ arrayNode('hosts')
Loading history...
345
                            ->beforeNormalization()->castToArray()->end()
346
                            ->defaultValue([])
347
                            ->prototype('scalar')->end()
348
                        ->end()
349
                        ->arrayNode('mapping')
350
                            ->normalizeKeys(false)
351
                            ->useAttributeAsKey('resource_class')
352
                            ->prototype('array')
353
                                ->children()
354
                                    ->scalarNode('index')->defaultNull()->end()
355
                                    ->scalarNode('type')->defaultValue(DocumentMetadata::DEFAULT_TYPE)->end()
356
                                ->end()
357
                            ->end()
358
                        ->end()
359
                    ->end()
360
                ->end()
361
            ->end();
362
    }
363
364
    /**
365
     * @throws InvalidConfigurationException
366
     */
367
    private function addExceptionToStatusSection(ArrayNodeDefinition $rootNode): void
368
    {
369
        $rootNode
370
            ->children()
371
                ->arrayNode('exception_to_status')
372
                    ->defaultValue([
373
                        ExceptionInterface::class => Response::HTTP_BAD_REQUEST,
374
                        InvalidArgumentException::class => Response::HTTP_BAD_REQUEST,
375
                        FilterValidationException::class => Response::HTTP_BAD_REQUEST,
376
                        OptimisticLockException::class => Response::HTTP_CONFLICT,
377
                    ])
378
                    ->info('The list of exceptions mapped to their HTTP status code.')
379
                    ->normalizeKeys(false)
380
                    ->useAttributeAsKey('exception_class')
381
                    ->beforeNormalization()
382
                        ->ifArray()
383
                        ->then(function (array $exceptionToStatus) {
384
                            foreach ($exceptionToStatus as &$httpStatusCode) {
385
                                if (\is_int($httpStatusCode)) {
386
                                    continue;
387
                                }
388
389
                                if (\defined($httpStatusCodeConstant = sprintf('%s::%s', Response::class, $httpStatusCode))) {
390
                                    @trigger_error(sprintf('Using a string "%s" as a constant of the "%s" class is deprecated since API Platform 2.1 and will not be possible anymore in API Platform 3. Use the Symfony\'s custom YAML extension for PHP constants instead (i.e. "!php/const %s").', $httpStatusCode, Response::class, $httpStatusCodeConstant), E_USER_DEPRECATED);
391
392
                                    $httpStatusCode = \constant($httpStatusCodeConstant);
393
                                }
394
                            }
395
396
                            return $exceptionToStatus;
397
                        })
398
                    ->end()
399
                    ->prototype('integer')->end()
400
                    ->validate()
401
                        ->ifArray()
402
                        ->then(function (array $exceptionToStatus) {
403
                            foreach ($exceptionToStatus as $httpStatusCode) {
404
                                if ($httpStatusCode < 100 || $httpStatusCode >= 600) {
405
                                    throw new InvalidConfigurationException(sprintf('The HTTP status code "%s" is not valid.', $httpStatusCode));
406
                                }
407
                            }
408
409
                            return $exceptionToStatus;
410
                        })
411
                    ->end()
412
                ->end()
413
            ->end();
414
    }
415
416
    private function addFormatSection(ArrayNodeDefinition $rootNode, string $key, array $defaultValue): void
417
    {
418
        $rootNode
419
            ->children()
420
                ->arrayNode($key)
421
                    ->defaultValue($defaultValue)
422
                    ->info('The list of enabled formats. The first one will be the default.')
423
                    ->normalizeKeys(false)
424
                    ->useAttributeAsKey('format')
425
                    ->beforeNormalization()
426
                        ->ifArray()
427
                        ->then(function ($v) {
428
                            foreach ($v as $format => $value) {
429
                                if (isset($value['mime_types'])) {
430
                                    continue;
431
                                }
432
433
                                $v[$format] = ['mime_types' => $value];
434
                            }
435
436
                            return $v;
437
                        })
438
                    ->end()
439
                    ->prototype('array')
440
                        ->children()
441
                            ->arrayNode('mime_types')->prototype('scalar')->end()->end()
442
                        ->end()
443
                    ->end()
444
                ->end()
445
            ->end();
446
    }
447
}
448