-
-
Notifications
You must be signed in to change notification settings - Fork 961
Expand file tree
/
Copy pathConfiguration.php
More file actions
759 lines (710 loc) · 39.9 KB
/
Configuration.php
File metadata and controls
759 lines (710 loc) · 39.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
<?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ApiPlatform\Symfony\Bundle\DependencyInjection;
use ApiPlatform\Doctrine\Common\Filter\OrderFilterInterface;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Exception\InvalidArgumentException;
use ApiPlatform\Metadata\Parameter;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Metadata\Put;
use ApiPlatform\Symfony\Controller\MainController;
use Composer\InstalledVersions;
use Doctrine\Bundle\DoctrineBundle\DoctrineBundle;
use Doctrine\Bundle\MongoDBBundle\DoctrineMongoDBBundle;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\OptimisticLockException;
use GraphQL\GraphQL;
use Symfony\Bundle\FrameworkBundle\Controller\ControllerHelper;
use Symfony\Bundle\FullStack;
use Symfony\Bundle\MakerBundle\MakerBundle;
use Symfony\Bundle\MercureBundle\MercureBundle;
use Symfony\Bundle\TwigBundle\TwigBundle;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\JsonStreamer\JsonStreamWriter;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Serializer\Exception\ExceptionInterface as SerializerExceptionInterface;
use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter;
use Symfony\Component\Yaml\Yaml;
/**
* The configuration of the bundle.
*
* @author Kévin Dunglas <dunglas@gmail.com>
* @author Baptiste Meyer <baptiste.meyer@gmail.com>
*/
final class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder('api_platform');
$rootNode = $treeBuilder->getRootNode();
$jsonLdInstalled = InstalledVersions::isInstalled('api-platform/jsonld') && InstalledVersions::isInstalled('api-platform/hydra');
$rootNode
->beforeNormalization()
->ifTrue(static function ($v) {
return false === ($v['enable_swagger'] ?? null);
})
->then(static function ($v) {
$v['swagger']['versions'] = [];
return $v;
})
->end()
->children()
->scalarNode('title')
->info('The title of the API.')
->cannotBeEmpty()
->defaultValue('')
->end()
->scalarNode('description')
->info('The description of the API.')
->cannotBeEmpty()
->defaultValue('')
->end()
->scalarNode('version')
->info('The version of the API.')
->cannotBeEmpty()
->defaultValue('0.0.0')
->end()
->booleanNode('show_webby')->defaultTrue()->info('If true, show Webby on the documentation page')->end()
->booleanNode('use_symfony_listeners')->defaultFalse()->info(sprintf('Uses Symfony event listeners instead of the %s.', MainController::class))->end()
->scalarNode('name_converter')->defaultNull()->info('Specify a name converter to use.')->end()
->scalarNode('asset_package')->defaultNull()->info('Specify an asset package name to use.')->end()
->scalarNode('path_segment_name_generator')->defaultValue('api_platform.metadata.path_segment_name_generator.underscore')->info('Specify a path name generator to use.')->end()
->scalarNode('inflector')->defaultValue('api_platform.metadata.inflector')->info('Specify an inflector to use.')->end()
->arrayNode('validator')
->addDefaultsIfNotSet()
->children()
->variableNode('serialize_payload_fields')->defaultValue([])->info('Set to null to serialize all payload fields when a validation error is thrown, or set the fields you want to include explicitly.')->end()
->booleanNode('query_parameter_validation')
->defaultValue(true)
->setDeprecated('api-platform/symfony', '4.2', 'Will be removed in API Platform 5.0.')
->end()
->end()
->end()
// TODO 4.4: deprecate use_iri_as_id defaulting to true
->arrayNode('jsonapi')
->addDefaultsIfNotSet()
->children()
->booleanNode('use_iri_as_id')
->defaultTrue()
->info('Set to false to use entity identifiers instead of IRIs as the "id" field in JSON:API responses.')
->end()
->end()
->end()
->arrayNode('eager_loading')
->canBeDisabled()
->addDefaultsIfNotSet()
->children()
->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()
->integerNode('max_joins')->defaultValue(30)->info('Max number of joined relations before EagerLoading throws a RuntimeException')->end()
->booleanNode('force_eager')->defaultTrue()->info('Force join on every relation. If disabled, it will only join relations having the EAGER fetch mode.')->end()
->end()
->end()
->booleanNode('handle_symfony_errors')->defaultFalse()->info('Allows to handle symfony exceptions.')->end()
->booleanNode('enable_swagger')->defaultTrue()->info('Enable the Swagger documentation and export.')->end()
->booleanNode('enable_json_streamer')->defaultValue(class_exists(ControllerHelper::class) && class_exists(JsonStreamWriter::class))->info('Enable json streamer.')->end()
->booleanNode('enable_swagger_ui')->defaultValue(class_exists(TwigBundle::class))->info('Enable Swagger UI')->end()
->booleanNode('enable_re_doc')->defaultValue(class_exists(TwigBundle::class))->info('Enable ReDoc')->end()
->booleanNode('enable_scalar')->defaultValue(class_exists(TwigBundle::class))->info('Enable Scalar API Reference')->end()
->booleanNode('enable_entrypoint')->defaultTrue()->info('Enable the entrypoint')->end()
->booleanNode('enable_docs')->defaultTrue()->info('Enable the docs')->end()
->booleanNode('enable_profiler')->defaultTrue()->info('Enable the data collector and the WebProfilerBundle integration.')->end()
->booleanNode('enable_phpdoc_parser')->defaultTrue()->info('Enable resource metadata collector using PHPStan PhpDocParser.')->end()
->booleanNode('enable_link_security')
->defaultTrue()
->info('Enable security for Links (sub resources).')
->setDeprecated('api-platform/symfony', '4.2', 'This option is always enabled and will be removed in API Platform 5.0.')
->end()
->arrayNode('collection')
->addDefaultsIfNotSet()
->children()
->scalarNode('exists_parameter_name')->defaultValue('exists')->cannotBeEmpty()->info('The name of the query parameter to filter on nullable field values.')->end()
->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
->scalarNode('order_parameter_name')->defaultValue('order')->cannotBeEmpty()->info('The name of the query parameter to order results.')->end()
->enumNode('order_nulls_comparison')->defaultNull()->values(interface_exists(OrderFilterInterface::class) ? array_merge(array_keys(OrderFilterInterface::NULLS_DIRECTION_MAP), [null]) : [null])->info('The nulls comparison strategy.')->end()
->arrayNode('pagination')
->canBeDisabled()
->addDefaultsIfNotSet()
->children()
->scalarNode('page_parameter_name')->defaultValue('page')->cannotBeEmpty()->info('The default name of the parameter handling the page number.')->end()
->scalarNode('enabled_parameter_name')->defaultValue('pagination')->cannotBeEmpty()->info('The name of the query parameter to enable or disable pagination.')->end()
->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()
->scalarNode('partial_parameter_name')->defaultValue('partial')->cannotBeEmpty()->info('The name of the query parameter to enable or disable partial pagination.')->end()
->end()
->end()
->end()
->end()
->arrayNode('mapping')
->addDefaultsIfNotSet()
->children()
->arrayNode('imports')
->prototype('scalar')->end()
->end()
->arrayNode('paths')
->prototype('scalar')->end()
->end()
->end()
->end()
->arrayNode('resource_class_directories')
->prototype('scalar')->end()
->setDeprecated('api-platform/symfony', '4.1', 'The "resource_class_directories" configuration is deprecated, classes using #[ApiResource] attribute are autoconfigured by the dependency injection container.')
->end()
->arrayNode('serializer')
->addDefaultsIfNotSet()
->children()
->booleanNode('hydra_prefix')->defaultFalse()->info('Use the "hydra:" prefix.')->end()
->end()
->end()
->end();
$this->addDoctrineOrmSection($rootNode);
$this->addDoctrineMongoDbOdmSection($rootNode);
$this->addOAuthSection($rootNode);
$this->addGraphQlSection($rootNode);
$this->addSwaggerSection($rootNode);
$this->addHttpCacheSection($rootNode);
$this->addMercureSection($rootNode);
$this->addMessengerSection($rootNode);
$this->addElasticsearchSection($rootNode);
$this->addOpenApiSection($rootNode);
$this->addMakerSection($rootNode);
$this->addMcpSection($rootNode);
$this->addExceptionToStatusSection($rootNode);
$this->addFormatSection($rootNode, 'formats', $jsonLdInstalled ? [
'jsonld' => ['mime_types' => ['application/ld+json']]
] : [
'json' => ['mime_types' => ['application/json']]
]);
$this->addFormatSection($rootNode, 'patch_formats', [
'json' => ['mime_types' => ['application/merge-patch+json']],
]);
$defaultDocFormats = $jsonLdInstalled ? ['jsonld' => ['mime_types' => ['application/ld+json']]] : [];
$defaultDocFormats += [
'jsonopenapi' => ['mime_types' => ['application/vnd.openapi+json']],
'html' => ['mime_types' => ['text/html']],
];
if (class_exists(Yaml::class)) {
$defaultDocFormats['yamlopenapi'] = ['mime_types' => ['application/vnd.openapi+yaml']];
}
$this->addFormatSection($rootNode, 'docs_formats', $defaultDocFormats);
$defaultDocFormats = $jsonLdInstalled ? ['jsonld' => ['mime_types' => ['application/ld+json']]] : [];
$defaultDocFormats += [
'jsonopenapi' => ['mime_types' => ['application/vnd.openapi+json']],
'html' => ['mime_types' => ['text/html']],
];
$defaultErrorFormats = $jsonLdInstalled ? ['jsonld' => ['mime_types' => ['application/ld+json']]] : [];
$defaultErrorFormats += [
'jsonproblem' => ['mime_types' => ['application/problem+json']],
'json' => ['mime_types' => ['application/problem+json', 'application/json']],
];
$this->addFormatSection($rootNode, 'error_formats', $defaultErrorFormats);
$rootNode
->children()
->arrayNode('jsonschema_formats')
->scalarPrototype()->end()
->defaultValue([])
->info('The JSON formats to compute the JSON Schemas for.')
->end()
->end();
$this->addDefaultsSection($rootNode);
return $treeBuilder;
}
private function addDoctrineOrmSection(ArrayNodeDefinition $rootNode): void
{
$rootNode
->children()
->arrayNode('doctrine')
->{class_exists(DoctrineBundle::class) && interface_exists(EntityManagerInterface::class) ? 'canBeDisabled' : 'canBeEnabled'}()
->end()
->end();
}
private function addDoctrineMongoDbOdmSection(ArrayNodeDefinition $rootNode): void
{
$rootNode
->children()
->arrayNode('doctrine_mongodb_odm')
->{class_exists(DoctrineMongoDBBundle::class) ? 'canBeDisabled' : 'canBeEnabled'}()
->end()
->end();
}
private function addOAuthSection(ArrayNodeDefinition $rootNode): void
{
$rootNode
->children()
->arrayNode('oauth')
->canBeEnabled()
->addDefaultsIfNotSet()
->children()
->scalarNode('clientId')->defaultValue('')->info('The oauth client id.')->end()
->scalarNode('clientSecret')
->defaultValue('')
->info('The OAuth client secret. Never use this parameter in your production environment. It exposes crucial security information. This feature is intended for dev/test environments only. Enable "oauth.pkce" instead')
->end()
->booleanNode('pkce')->defaultFalse()->info('Enable the oauth PKCE.')->end()
->scalarNode('type')->defaultValue('oauth2')->info('The oauth type.')->end()
->scalarNode('flow')->defaultValue('application')->info('The oauth flow grant type.')->end()
->scalarNode('tokenUrl')->defaultValue('')->info('The oauth token url.')->end()
->scalarNode('authorizationUrl')->defaultValue('')->info('The oauth authentication url.')->end()
->scalarNode('refreshUrl')->defaultValue('')->info('The oauth refresh url.')->end()
->arrayNode('scopes')
->normalizeKeys(false)
->prototype('scalar')->end()
->end()
->end()
->end()
->end();
}
private function addGraphQlSection(ArrayNodeDefinition $rootNode): void
{
$rootNode
->children()
->arrayNode('graphql')
->{class_exists(GraphQL::class) ? 'canBeDisabled' : 'canBeEnabled'}()
->addDefaultsIfNotSet()
->children()
->scalarNode('default_ide')->defaultValue('graphiql')->end()
->arrayNode('graphiql')
->{class_exists(GraphQL::class) && class_exists(TwigBundle::class) ? 'canBeDisabled' : 'canBeEnabled'}()
->end()
->arrayNode('introspection')
->canBeDisabled()
->end()
->integerNode('max_query_depth')->defaultValue(20)
->end()
->arrayNode('graphql_playground')
->setDeprecated('api-platform/core', '4.0', 'The "graphql_playground" configuration is deprecated and will be ignored.')
->canBeEnabled()
->end()
->integerNode('max_query_complexity')->defaultValue(500)
->end()
->scalarNode('nesting_separator')->defaultValue('_')->info('The separator to use to filter nested fields.')->end()
->arrayNode('collection')
->addDefaultsIfNotSet()
->children()
->arrayNode('pagination')
->canBeDisabled()
->end()
->end()
->end()
->end()
->end()
->end();
}
private function addSwaggerSection(ArrayNodeDefinition $rootNode): void
{
$supportedVersions = [3];
$rootNode
->children()
->arrayNode('swagger')
->addDefaultsIfNotSet()
->children()
->booleanNode('persist_authorization')->defaultValue(false)->info('Persist the SwaggerUI Authorization in the localStorage.')->end()
->arrayNode('versions')
->info('The active versions of OpenAPI to be exported or used in Swagger UI. The first value is the default.')
->defaultValue($supportedVersions)
->beforeNormalization()
->always(static function ($v): array {
if (!\is_array($v)) {
$v = [$v];
}
foreach ($v as &$version) {
$version = (int) $version;
}
return $v;
})
->end()
->validate()
->ifTrue(static fn ($v): bool => $v !== array_intersect($v, $supportedVersions))
->thenInvalid(sprintf('Only the versions %s are supported. Got %s.', implode(' and ', $supportedVersions), '%s'))
->end()
->prototype('scalar')->end()
->end()
->arrayNode('api_keys')
->useAttributeAsKey('key')
->validate()
->ifTrue(static fn ($v): bool => (bool) array_filter(array_keys($v), fn ($item) => !preg_match('/^[a-zA-Z0-9._-]+$/', $item)))
->thenInvalid('The api keys "key" is not valid according to the pattern enforced by OpenAPI 3.1 ^[a-zA-Z0-9._-]+$.')
->end()
->prototype('array')
->children()
->scalarNode('name')
->info('The name of the header or query parameter containing the api key.')
->end()
->enumNode('type')
->info('Whether the api key should be a query parameter or a header.')
->values(['query', 'header'])
->end()
->end()
->end()
->end()
->arrayNode('http_auth')
->info('Creates http security schemes for OpenAPI.')
->useAttributeAsKey('key')
->validate()
->ifTrue(static fn ($v): bool => (bool) array_filter(array_keys($v), fn ($item) => !preg_match('/^[a-zA-Z0-9._-]+$/', $item)))
->thenInvalid('The api keys "key" is not valid according to the pattern enforced by OpenAPI 3.1 ^[a-zA-Z0-9._-]+$.')
->end()
->prototype('array')
->children()
->scalarNode('scheme')
->info('The OpenAPI HTTP auth scheme, for example "bearer"')
->end()
->scalarNode('bearerFormat')
->info('The OpenAPI HTTP bearer format')
->end()
->end()
->end()
->end()
->variableNode('swagger_ui_extra_configuration')
->defaultValue([])
->validate()
->ifTrue(static fn ($v): bool => false === \is_array($v))
->thenInvalid('The swagger_ui_extra_configuration parameter must be an array.')
->end()
->info('To pass extra configuration to Swagger UI, like docExpansion or filter.')
->end()
->end()
->end()
->end();
}
private function addHttpCacheSection(ArrayNodeDefinition $rootNode): void
{
$rootNode
->children()
->arrayNode('http_cache')
->addDefaultsIfNotSet()
->children()
->booleanNode('public')->defaultNull()->info('To make all responses public by default.')->end()
->arrayNode('invalidation')
->info('Enable the tags-based cache invalidation system.')
->canBeEnabled()
->children()
->arrayNode('varnish_urls')
->setDeprecated('api-platform/core', '3.0', 'The "varnish_urls" configuration is deprecated, use "urls" or "scoped_clients".')
->defaultValue([])
->prototype('scalar')->end()
->info('URLs of the Varnish servers to purge using cache tags when a resource is updated.')
->end()
->arrayNode('urls')
->defaultValue([])
->prototype('scalar')->end()
->info('URLs of the Varnish servers to purge using cache tags when a resource is updated.')
->end()
->arrayNode('scoped_clients')
->defaultValue([])
->prototype('scalar')->end()
->info('Service names of scoped client to use by the cache purger.')
->end()
->integerNode('max_header_length')
->defaultValue(7500)
->info('Max header length supported by the cache server.')
->end()
->variableNode('request_options')
->defaultValue([])
->validate()
->ifTrue(static fn ($v): bool => false === \is_array($v))
->thenInvalid('The request_options parameter must be an array.')
->end()
->info('To pass options to the client charged with the request.')
->end()
->scalarNode('purger')
->defaultValue('api_platform.http_cache.purger.varnish')
->info('Specify a purger to use (available values: "api_platform.http_cache.purger.varnish.ban", "api_platform.http_cache.purger.varnish.xkey", "api_platform.http_cache.purger.souin").')
->end()
->arrayNode('xkey')
->setDeprecated('api-platform/core', '3.0', 'The "xkey" configuration is deprecated, use your own purger to customize surrogate keys or the appropriate parameters.')
->addDefaultsIfNotSet()
->children()
->scalarNode('glue')
->defaultValue(' ')
->info('xkey glue between keys')
->end()
->end()
->end()
->end()
->end()
->end()
->end()
->end();
}
private function addMercureSection(ArrayNodeDefinition $rootNode): void
{
$rootNode
->children()
->arrayNode('mercure')
->{class_exists(MercureBundle::class) ? 'canBeDisabled' : 'canBeEnabled'}()
->children()
->scalarNode('hub_url')
->defaultNull()
->info('The URL sent in the Link HTTP header. If not set, will default to the URL for MercureBundle\'s default hub.')
->end()
->booleanNode('include_type')
->defaultFalse()
->info('Always include @type in updates (including delete ones).')
->end()
->end()
->end()
->end();
}
private function addMessengerSection(ArrayNodeDefinition $rootNode): void
{
$rootNode
->children()
->arrayNode('messenger')
->{!class_exists(FullStack::class) && interface_exists(MessageBusInterface::class) ? 'canBeDisabled' : 'canBeEnabled'}()
->end()
->end();
}
private function addElasticsearchSection(ArrayNodeDefinition $rootNode): void
{
$rootNode
->children()
->arrayNode('elasticsearch')
->canBeEnabled()
->addDefaultsIfNotSet()
->validate()
->ifTrue(static fn (array $v): bool => null !== ($v['ssl_ca_bundle'] ?? null) && false === ($v['ssl_verification'] ?? true))
->thenInvalid('The "ssl_ca_bundle" and "ssl_verification: false" options cannot be used together. Either provide a CA bundle path or disable SSL verification, not both.')
->end()
->children()
->booleanNode('enabled')
->defaultFalse()
->validate()
->ifTrue()
->then(static function (bool $v): bool {
if (
// ES v7
!class_exists(\Elasticsearch\Client::class)
// ES v8 and up
&& !class_exists(\Elastic\Elasticsearch\Client::class)
// OpenSearch
&& !class_exists(\OpenSearch\Client::class)
) {
throw new InvalidConfigurationException('The elasticsearch/elasticsearch or opensearch-project/opensearch-php package is required for Elasticsearch support.');
}
return $v;
})
->end()
->end()
->arrayNode('hosts')
->beforeNormalization()->castToArray()->end()
->defaultValue([])
->prototype('scalar')->end()
->end()
->scalarNode('ssl_ca_bundle')
->defaultNull()
->info('Path to the SSL CA bundle file for Elasticsearch SSL verification.')
->end()
->booleanNode('ssl_verification')
->defaultTrue()
->info('Enable or disable SSL verification for Elasticsearch connections.')
->end()
->enumNode('client')
->values(['elasticsearch', 'opensearch'])
->defaultValue('elasticsearch')
->info('The search engine client to use: "elasticsearch" or "opensearch".')
->validate()
->ifString()
->then(static function (string $v): string {
if ('opensearch' === $v && !class_exists(\OpenSearch\Client::class)) {
throw new InvalidConfigurationException('Setting api_platform.elasticsearch.client to "opensearch" requires the opensearch-project/opensearch-php package. Try running "composer require opensearch-project/opensearch-php".');
}
return $v;
})
->end()
->end()
->end()
->end()
->end();
}
private function addOpenApiSection(ArrayNodeDefinition $rootNode): void
{
$rootNode
->children()
->arrayNode('openapi')
->addDefaultsIfNotSet()
->children()
->arrayNode('contact')
->addDefaultsIfNotSet()
->children()
->scalarNode('name')->defaultNull()->info('The identifying name of the contact person/organization.')->end()
->scalarNode('url')->defaultNull()->info('The URL pointing to the contact information. MUST be in the format of a URL.')->end()
->scalarNode('email')->defaultNull()->info('The email address of the contact person/organization. MUST be in the format of an email address.')->end()
->end()
->end()
->scalarNode('termsOfService')->defaultNull()->info('A URL to the Terms of Service for the API. MUST be in the format of a URL.')->end()
->arrayNode('tags')
->info('Global OpenApi tags overriding the default computed tags if specified.')
->prototype('array')
->children()
->scalarNode('name')->isRequired()->end()
->scalarNode('description')->defaultNull()->end()
->end()
->end()
->end()
->arrayNode('license')
->addDefaultsIfNotSet()
->children()
->scalarNode('name')->defaultNull()->info('The license name used for the API.')->end()
->scalarNode('url')->defaultNull()->info('URL to the license used for the API. MUST be in the format of a URL.')->end()
->scalarNode('identifier')->defaultNull()->info('An SPDX license expression for the API. The identifier field is mutually exclusive of the url field.')->end()
->end()
->end()
->variableNode('swagger_ui_extra_configuration')
->defaultValue([])
->validate()
->ifTrue(static fn ($v): bool => false === \is_array($v))
->thenInvalid('The swagger_ui_extra_configuration parameter must be an array.')
->end()
->info('To pass extra configuration to Swagger UI, like docExpansion or filter.')
->end()
->variableNode('scalar_extra_configuration')
->defaultValue([])
->validate()
->ifTrue(static fn ($v): bool => false === \is_array($v))
->thenInvalid('The scalar_extra_configuration parameter must be an array.')
->end()
->info('To pass extra configuration to Scalar API Reference, like theme or darkMode.')
->end()
->booleanNode('overrideResponses')->defaultTrue()->info('Whether API Platform adds automatic responses to the OpenAPI documentation.')->end()
->scalarNode('error_resource_class')->defaultNull()->info('The class used to represent errors in the OpenAPI documentation.')->end()
->scalarNode('validation_error_resource_class')->defaultNull()->info('The class used to represent validation errors in the OpenAPI documentation.')->end()
->end()
->end()
->end();
}
/**
* @throws InvalidConfigurationException
*/
private function addExceptionToStatusSection(ArrayNodeDefinition $rootNode): void
{
$rootNode
->children()
->arrayNode('exception_to_status')
->defaultValue([
SerializerExceptionInterface::class => Response::HTTP_BAD_REQUEST,
InvalidArgumentException::class => Response::HTTP_BAD_REQUEST,
OptimisticLockException::class => Response::HTTP_CONFLICT,
])
->info('The list of exceptions mapped to their HTTP status code.')
->normalizeKeys(false)
->useAttributeAsKey('exception_class')
->prototype('integer')->end()
->validate()
->ifArray()
->then(static function (array $exceptionToStatus): array {
foreach ($exceptionToStatus as $httpStatusCode) {
if ($httpStatusCode < 100 || $httpStatusCode >= 600) {
throw new InvalidConfigurationException(sprintf('The HTTP status code "%s" is not valid.', $httpStatusCode));
}
}
return $exceptionToStatus;
})
->end()
->end()
->end();
}
private function addFormatSection(ArrayNodeDefinition $rootNode, string $key, array $defaultValue): void
{
$rootNode
->children()
->arrayNode($key)
->defaultValue($defaultValue)
->info('The list of enabled formats. The first one will be the default.')
->normalizeKeys(false)
->useAttributeAsKey('format')
->beforeNormalization()
->ifArray()
->then(static function ($v) {
foreach ($v as $format => $value) {
if (isset($value['mime_types'])) {
continue;
}
$v[$format] = ['mime_types' => $value];
}
return $v;
})
->end()
->prototype('array')
->children()
->arrayNode('mime_types')->prototype('scalar')->end()->end()
->end()
->end()
->end()
->end();
}
private function addDefaultsSection(ArrayNodeDefinition $rootNode): void
{
$nameConverter = new CamelCaseToSnakeCaseNameConverter();
$defaultsNode = $rootNode->children()->arrayNode('defaults');
$defaultsNode
->ignoreExtraKeys(false)
->beforeNormalization()
->always(static function (array $defaults) use ($nameConverter): array {
$normalizedDefaults = [];
foreach ($defaults as $option => $value) {
$option = $nameConverter->normalize($option);
$normalizedDefaults[$option] = $value;
}
return $normalizedDefaults;
});
$this->defineDefault($defaultsNode, new \ReflectionClass(ApiResource::class), $nameConverter);
$this->defineDefault($defaultsNode, new \ReflectionClass(Put::class), $nameConverter);
$this->defineDefault($defaultsNode, new \ReflectionClass(Post::class), $nameConverter);
$parametersNode = $defaultsNode
->children()
->arrayNode('parameters')
->info('Global parameters applied to all resources and operations.')
->useAttributeAsKey('parameter_class')
->prototype('array')
->ignoreExtraKeys(false);
$this->defineDefault($parametersNode, new \ReflectionClass(Parameter::class), $nameConverter);
$parametersNode->end()->end()->end();
}
private function addMakerSection(ArrayNodeDefinition $rootNode): void
{
$rootNode
->children()
->arrayNode('maker')
->{class_exists(MakerBundle::class) ? 'canBeDisabled' : 'canBeEnabled'}()
->children()
->scalarNode('namespace_prefix')->defaultValue('')->info('Add a prefix to all maker generated classes. e.g set it to "Api" to set the maker namespace to "App\\Api\\" (if the maker.root_namespace config is App). e.g. App\\Api\\State\\MyStateProcessor')->end()
->end()
->end()
->end();
}
private function addMcpSection(ArrayNodeDefinition $rootNode): void
{
$rootNode
->children()
->arrayNode('mcp')
->canBeDisabled()
->children()
->scalarNode('format')
->defaultValue('jsonld')
->info('The serialization format used for MCP tool input/output. Must be a format registered in api_platform.formats (e.g. "jsonld", "json", "jsonapi").')
->end()
->end()
->end()
->end();
}
private function defineDefault(ArrayNodeDefinition $defaultsNode, \ReflectionClass $reflectionClass, CamelCaseToSnakeCaseNameConverter $nameConverter): void
{
foreach ($reflectionClass->getConstructor()->getParameters() as $parameter) {
$defaultsNode->children()->variableNode($nameConverter->normalize($parameter->getName()));
}
}
}