Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit008ee37

Browse files
committed
Generate JSON schema for config
1 parentd4566b2 commit008ee37

File tree

14 files changed

+1451
-68
lines changed

14 files changed

+1451
-68
lines changed

‎src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ CHANGELOG
99
* Add JsonEncoder services and configuration
1010
* Add new`framework.property_info.with_constructor_extractor` option to allow enabling or disabling the constructor extractor integration
1111
* Deprecate the`--show-arguments` option of the`container:debug` command, as arguments are now always shown
12+
* Generate JSON schema for YAML configuration
1213

1314
7.2
1415
---
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
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+
namespaceSymfony\Bundle\FrameworkBundle\CacheWarmer;
13+
14+
usePsr\Log\LoggerInterface;
15+
useSymfony\Component\Config\Definition\ArrayNode;
16+
useSymfony\Component\Config\Definition\ConfigurationInterface;
17+
useSymfony\Component\Config\Definition\JsonSchemaGenerator;
18+
useSymfony\Component\DependencyInjection\Container;
19+
useSymfony\Component\DependencyInjection\ContainerBuilder;
20+
useSymfony\Component\DependencyInjection\Extension\ConfigurationExtensionInterface;
21+
useSymfony\Component\DependencyInjection\ParameterBag\ContainerBag;
22+
useSymfony\Component\DependencyInjection\ParameterBag\ParameterBag;
23+
useSymfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
24+
useSymfony\Component\HttpKernel\Kernel;
25+
useSymfony\Component\HttpKernel\KernelInterface;
26+
27+
/**
28+
* Generate config json schema.
29+
*/
30+
finalreadonlyclass ConfigSchemaCacheWarmerimplements CacheWarmerInterface
31+
{
32+
publicfunction__construct(
33+
privateKernelInterface$kernel,
34+
private ?LoggerInterface$logger =null,
35+
) {
36+
}
37+
38+
publicfunctionwarmUp(string$cacheDir, ?string$buildDir =null):array
39+
{
40+
if (!$buildDir || !$this->kernel->isDebug() || !class_exists(JsonSchemaGenerator::class)) {
41+
return [];
42+
}
43+
44+
$generator =newJsonSchemaGenerator($buildDir.'/config.schema.json');
45+
46+
if ($this->kernelinstanceof Kernel) {
47+
/** @var ContainerBuilder $container */
48+
$container = \Closure::bind(function (Kernel$kernel) {
49+
$containerBuilder =$kernel->getContainerBuilder();
50+
$kernel->prepareContainer($containerBuilder);
51+
52+
return$containerBuilder;
53+
},null,$this->kernel)($this->kernel);
54+
55+
$extensions =$container->getExtensions();
56+
}else {
57+
$extensions = [];
58+
foreach ($this->kernel->getBundles()as$bundle) {
59+
$extension =$bundle->getContainerExtension();
60+
if (null !==$extension) {
61+
$extensions[] =$extension;
62+
}
63+
}
64+
}
65+
66+
$tree =newArrayNode(null);
67+
foreach ($extensionsas$extension) {
68+
try {
69+
$configuration =null;
70+
if ($extensioninstanceof ConfigurationInterface) {
71+
$configuration =$extension;
72+
}elseif ($extensioninstanceof ConfigurationExtensionInterface) {
73+
$container =$this->kernel->getContainer();
74+
$configuration =$extension->getConfiguration([],newContainerBuilder($containerinstanceof Container ?newContainerBag($container) :newParameterBag()));
75+
}
76+
77+
if (!$extensionConfigNode =$configuration?->getConfigTreeBuilder()->buildTree()) {
78+
continue;
79+
}
80+
81+
$tree->addChild($extensionConfigNode);
82+
}catch (\Exception$e) {
83+
$this->logger?->warning('Failed to generate JSON schema for extension {extensionClass}:'.$e->getMessage(), ['exception' =>$e,'extensionClass' =>$extension::class]);
84+
}
85+
}
86+
87+
try {
88+
$generator->build($tree, [
89+
'description' =>'Symfony configuration',
90+
'patternProperties' => [
91+
'when@[a-zA-Z0-9]+' => ['$ref' =>'#/definitions/root'],
92+
],
93+
]);
94+
}catch (\Exception$e) {
95+
$this->logger?->warning('Failed to generate JSON schema for the configuration:'.$e->getMessage(), ['exception' =>$e]);
96+
}
97+
98+
// No need to preload anything
99+
return [];
100+
}
101+
102+
publicfunctionisOptional():bool
103+
{
104+
returnfalse;
105+
}
106+
}

‎src/Symfony/Bundle/FrameworkBundle/Resources/config/services.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
usePsr\Clock\ClockInterfaceasPsrClockInterface;
1515
usePsr\EventDispatcher\EventDispatcherInterfaceasPsrEventDispatcherInterface;
1616
useSymfony\Bundle\FrameworkBundle\CacheWarmer\ConfigBuilderCacheWarmer;
17+
useSymfony\Bundle\FrameworkBundle\CacheWarmer\ConfigSchemaCacheWarmer;
1718
useSymfony\Bundle\FrameworkBundle\HttpCache\HttpCache;
1819
useSymfony\Component\Clock\Clock;
1920
useSymfony\Component\Clock\ClockInterface;
@@ -233,6 +234,10 @@ class_exists(WorkflowEvents::class) ? WorkflowEvents::ALIASES : []
233234
->args([service(KernelInterface::class),service('logger')->nullOnInvalid()])
234235
->tag('kernel.cache_warmer')
235236

237+
->set('config_schema.warmer', ConfigSchemaCacheWarmer::class)
238+
->args([service(KernelInterface::class),service('logger')->nullOnInvalid()])
239+
->tag('kernel.cache_warmer')
240+
236241
->set('clock', Clock::class)
237242
->alias(ClockInterface::class,'clock')
238243
->alias(PsrClockInterface::class,'clock')

‎src/Symfony/Component/Config/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ CHANGELOG
55
---
66

77
* Add`ExprBuilder::ifFalse()`
8+
* Add`JsonSchemaGenerator`
89

910
7.2
1011
---

‎src/Symfony/Component/Config/Definition/BaseNode.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,14 @@ public function addEquivalentValue(mixed $originalValue, mixed $equivalentValue)
167167
$this->equivalentValues[] = [$originalValue,$equivalentValue];
168168
}
169169

170+
/**
171+
* @internal
172+
*/
173+
publicfunctiongetEquivalentValues():array
174+
{
175+
return$this->equivalentValues;
176+
}
177+
170178
/**
171179
* Set this node as required.
172180
*/

‎src/Symfony/Component/Config/Definition/BooleanNode.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,14 @@ public function __construct(
2929
parent::__construct($name,$parent,$pathSeparator);
3030
}
3131

32+
/**
33+
* @internal
34+
*/
35+
publicfunctionisNullable():bool
36+
{
37+
return$this->nullable;
38+
}
39+
3240
protectedfunctionvalidateType(mixed$value):void
3341
{
3442
if (!\is_bool($value)) {
Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
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+
namespaceSymfony\Component\Config\Definition;
13+
14+
useSymfony\Component\Config\Definition\Builder\ExprBuilder;
15+
16+
/**
17+
* @experimental
18+
*/
19+
finalreadonlyclass JsonSchemaGenerator
20+
{
21+
publicfunction__construct(privatestring$outputPath)
22+
{
23+
}
24+
25+
publicfunctionbuild(NodeInterface$node,array$schema = []):void
26+
{
27+
$schema =array_replace_recursive([
28+
'$schema' =>'http://json-schema.org/draft-06/schema#',
29+
'definitions' => [
30+
'param' => [
31+
'$comment' =>'Container parameter',
32+
'type' =>'string',
33+
'pattern' =>'^%[^%]+%$',
34+
],
35+
'root' =>$this->buildSingleNode($node, allowParam:false),
36+
],
37+
'$ref' =>'#/definitions/root',
38+
],$schema);
39+
40+
file_put_contents($this->outputPath,json_encode($schema, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES | \JSON_THROW_ON_ERROR));
41+
}
42+
43+
privatefunctionbuildArrayNode(ArrayNode$node):array
44+
{
45+
$schema = [
46+
'type' => ['object','array'],
47+
'additionalProperties' =>$node->shouldIgnoreExtraKeys(),
48+
'maxItems' =>0,
49+
];
50+
51+
foreach ($node->getChildren()as$child) {
52+
$schema['properties'][$child->getName()] =$this->buildSingleNode($child);
53+
}
54+
55+
return$schema;
56+
}
57+
58+
privatefunctionbuildSingleNode(NodeInterface$node,bool$allowParam =true):array|\ArrayObject
59+
{
60+
$schema =match (\count($types =$this->createSubSchemas($node,$allowParam))) {
61+
1 =>$types[0],
62+
default => ['anyOf' =>$types],
63+
};
64+
65+
if ($node->hasDefaultValue()) {
66+
$schema['default'] =$node->getDefaultValue();
67+
}
68+
69+
if ($nodeinstanceof BaseNode) {
70+
if ($info =$node->getInfo()) {
71+
$schema['description'] =$info;
72+
}
73+
74+
if ($node->isDeprecated()) {
75+
$schema['deprecated'] =true;
76+
}
77+
}
78+
79+
return$schema;
80+
}
81+
82+
privatefunctioncreateSubSchemas(NodeInterface$node,bool$allowParam =true):array
83+
{
84+
$paramTypes = [];
85+
86+
$getType =fn ($value) =>match (get_debug_type($value)) {
87+
'string' =>'string',
88+
'int' =>'integer',
89+
default =>null,
90+
};
91+
92+
$removeNulls =fn (array$array) =>array_filter($array,fn ($value) =>null !==$value);
93+
94+
if ($nodeinstanceof BaseNode && !$nodeinstanceof StringNode &&\in_array(ExprBuilder::TYPE_STRING,$node->getNormalizedTypes(),true)) {
95+
$paramTypes[] = ['type' =>'string'];
96+
}
97+
98+
$pseudoType =match (true) {
99+
$nodeinstanceof BooleanNode =>'bool',
100+
$nodeinstanceof IntegerNode =>'int',
101+
$nodeinstanceof NumericNode =>'float',
102+
$nodeinstanceof StringNode =>'string',
103+
$nodeinstanceof EnumNode =>'enum',
104+
$nodeinstanceof PrototypedArrayNode =>'array_prototype',
105+
$nodeinstanceof ArrayNode =>'array',
106+
$nodeinstanceof ScalarNode =>'scalar',
107+
default =>null,
108+
};
109+
110+
$schema =match ($pseudoType) {
111+
'bool' => ['type' =>'boolean'],
112+
'int' =>$removeNulls(['type' =>'integer','minimum' =>$node->getMin(),'maximum' =>$node->getMax()]),
113+
'float' =>$removeNulls(['type' =>'number','minimum' =>$node->getMin(),'maximum' =>$node->getMax()]),
114+
'string' => ['type' =>'string'],
115+
'enum' =>$removeNulls(['enum' =>array_map(fn ($v) =>$vinstanceof \UnitEnum ?\sprintf('!php/enum %s::%s',$v::class,$v->name) :$v,$node->getValues()) ?:null]),
116+
'array_prototype' =>$this->buildPrototypedArray($node),
117+
'array' =>$this->buildArrayNode($node),
118+
'scalar' => ['type' => ['string','number','boolean']],
119+
default =>null,
120+
};
121+
122+
$allowNull = !($nodeinstanceof NumericNode) && (
123+
($nodeinstanceof BooleanNode &&$node->isNullable())
124+
|| ($node->isRequired() &&$nodeinstanceof StringNode &&$node->getAllowEmptyValue())
125+
|| (!$node->isRequired() && ($node->hasDefaultValue() || ($nodeinstanceof VariableNode &&$node->getAllowEmptyValue())))
126+
|| ($node->hasDefaultValue() &&null ===$node->getDefaultValue())
127+
);
128+
129+
if ($nodeinstanceof BaseNode) {
130+
$map =fn (array$mapping) =>match (true) {
131+
null ===$mapping[0] => !$allowNull,
132+
get_debug_type($mapping[0]) ===$pseudoType =>false,
133+
'scalar' ===$pseudoType => !\is_scalar($mapping[0]),
134+
default =>true,
135+
};
136+
if ($equivalentValues =array_column(array_filter($node->getEquivalentValues(),$map),0)) {
137+
if (!isset($schema['enum'])) {
138+
if (\in_array(true,$equivalentValues,true) &&\in_array(false,$equivalentValues,true)) {
139+
$schema['type'] = (array) ($schema['type'] ?? []);
140+
$schema['type'][] ='boolean';
141+
$equivalentValues =array_filter($equivalentValues,fn ($value) => !\is_bool($value));
142+
}
143+
if (\in_array(null,$equivalentValues,true)) {
144+
$allowNull =true;
145+
$equivalentValues =array_filter($equivalentValues,fn ($value) =>null !==$value);
146+
}
147+
148+
if ($equivalentValues) {
149+
$paramTypes[] = ['enum' =>array_values($equivalentValues)];
150+
}
151+
}else {
152+
$schema['enum'] =array_values(array_unique(array_merge($schema['enum'],$equivalentValues)));
153+
}
154+
}
155+
}
156+
157+
if ($schema) {
158+
$paramTypes[] =$schema;
159+
if ($allowParam) {
160+
$paramTypes[] = ['$ref' =>'#/definitions/param'];
161+
}
162+
}
163+
164+
if ($allowNull) {
165+
foreach ($paramTypesas &$subSchema) {
166+
if (!isset($subSchema['type'])) {
167+
continue;
168+
}
169+
170+
$subSchema['type'] = (array)$subSchema['type'];
171+
$subSchema['type'][] ='null';
172+
}
173+
}
174+
175+
return$paramTypes ?: [new \ArrayObject()];
176+
}
177+
178+
privatefunctionbuildPrototypedArray(PrototypedArrayNode$node):array
179+
{
180+
$items =$this->buildSingleNode($node->getPrototype());
181+
182+
$schema = ['type' => ['array','object'],'items' =>$items,'additionalProperties' =>$items];
183+
184+
if ($node->getMinNumberOfElements() >0) {
185+
$schema[0]['minItems'] =$schema[0]['minProperties'] =$node->getMinNumberOfElements();
186+
}
187+
188+
return$schema;
189+
}
190+
}

‎src/Symfony/Component/Config/Definition/NumericNode.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,22 @@ public function __construct(
3030
parent::__construct($name,$parent,$pathSeparator);
3131
}
3232

33+
/**
34+
* @internal
35+
*/
36+
publicfunctiongetMin():int|float|null
37+
{
38+
return$this->min;
39+
}
40+
41+
/**
42+
* @internal
43+
*/
44+
publicfunctiongetMax():int|float|null
45+
{
46+
return$this->max;
47+
}
48+
3349
protectedfunctionfinalizeValue(mixed$value):mixed
3450
{
3551
$value =parent::finalizeValue($value);

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp