Skip to content

[Config] Handle ignoreExtraKeys in config builder #40987

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 26, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion src/Symfony/Component/Config/Builder/ClassBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ class ClassBuilder
private $require = [];
private $use = [];
private $implements = [];
private $allowExtraKeys = false;

public function __construct(string $namespace, string $name)
{
Expand Down Expand Up @@ -127,7 +128,7 @@ public function addMethod(string $name, string $body, array $params = []): void

public function addProperty(string $name, string $classType = null): Property
{
$property = new Property($name, $this->camelCase($name));
$property = new Property($name, '_' !== $name[0] ? $this->camelCase($name) : $name);
if (null !== $classType) {
$property->setType($classType);
}
Expand Down Expand Up @@ -163,4 +164,14 @@ public function getFqcn(): string
{
return '\\'.$this->namespace.'\\'.$this->name;
}

public function setAllowExtraKeys(bool $allowExtraKeys): void
{
$this->allowExtraKeys = $allowExtraKeys;
}

public function shouldAllowExtraKeys(): bool
{
return $this->allowExtraKeys;
}
}
56 changes: 46 additions & 10 deletions src/Symfony/Component/Config/Builder/ConfigBuilderGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,7 @@ public function build(ConfigurationInterface $configuration): \Closure
public function NAME(): string
{
return \'ALIAS\';
}
', ['ALIAS' => $rootNode->getPath()]);
}', ['ALIAS' => $rootNode->getPath()]);

$this->writeClasses();
}
Expand Down Expand Up @@ -90,6 +89,7 @@ private function writeClasses(): void
foreach ($this->classes as $class) {
$this->buildConstructor($class);
$this->buildToArray($class);
$this->buildSetExtraKey($class);

file_put_contents($this->getFullPath($class), $class->build());
}
Expand Down Expand Up @@ -126,6 +126,7 @@ private function buildNode(NodeInterface $node, ClassBuilder $class, string $nam
private function handleArrayNode(ArrayNode $node, ClassBuilder $class, string $namespace): void
{
$childClass = new ClassBuilder($namespace, $node->getName());
$childClass->setAllowExtraKeys($node->shouldIgnoreExtraKeys());
$class->addRequire($childClass);
$this->classes[] = $childClass;

Expand Down Expand Up @@ -163,7 +164,7 @@ public function NAME($valueDEFAULT): self

return $this;
}';
$class->addMethod($node->getName(), $body, ['PROPERTY' => $property->getName(), 'COMMENT' => $comment, 'DEFAULT' => $node->hasDefaultValue() ? ' = '.var_export($node->getDefaultValue(), true) : '']);
$class->addMethod($node->getName(), $body, ['PROPERTY' => $property->getName(), 'COMMENT' => $comment, 'DEFAULT' => $node->hasDefaultValue() ? ' = '.var_export($node->getDefaultValue(), true) : '']);
}

private function handlePrototypedArrayNode(PrototypedArrayNode $node, ClassBuilder $class, string $namespace): void
Expand Down Expand Up @@ -211,6 +212,9 @@ public function NAME(string $VAR, $VALUE): self
}

$childClass = new ClassBuilder($namespace, $name);
if ($prototype instanceof ArrayNode) {
$childClass->setAllowExtraKeys($prototype->shouldIgnoreExtraKeys());
}
$class->addRequire($childClass);
$this->classes[] = $childClass;
$property = $class->addProperty($node->getName(), $childClass->getFqcn().'[]');
Expand Down Expand Up @@ -368,14 +372,15 @@ private function buildToArray(ClassBuilder $class): void
}', ['PROPERTY' => $p->getName(), 'ORG_NAME' => $p->getOriginalName()]);
}

$extraKeys = $class->shouldAllowExtraKeys() ? ' + $this->_extraKeys' : '';

$class->addMethod('toArray', '
public function NAME(): array
{
'.$body.'

return $output;
}
');
return $output'.$extraKeys.';
}');
}

private function buildConstructor(ClassBuilder $class): void
Expand All @@ -399,18 +404,49 @@ private function buildConstructor(ClassBuilder $class): void
', ['PROPERTY' => $p->getName(), 'ORG_NAME' => $p->getOriginalName()]);
}

$body .= '
if ($class->shouldAllowExtraKeys()) {
$body .= '
$this->_extraKeys = $value;
';
} else {
$body .= '
if ([] !== $value) {
throw new InvalidConfigurationException(sprintf(\'The following keys are not supported by "%s": \', __CLASS__).implode(\', \', array_keys($value)));
}';

$class->addUse(InvalidConfigurationException::class);
$class->addUse(InvalidConfigurationException::class);
}

$class->addMethod('__construct', '
public function __construct(array $value = [])
{
'.$body.'
}
');
}');
}

private function buildSetExtraKey(ClassBuilder $class): void
{
if (!$class->shouldAllowExtraKeys()) {
return;
}

$class->addProperty('_extraKeys');

$class->addMethod('set', '
/**
* @param ParamConfigurator|mixed $value
* @return $this
*/
public function NAME(string $key, $value): self
{
if (null === $value) {
unset($this->_extraKeys[$key]);
} else {
$this->_extraKeys[$key] = $value;
}

return $this;
}');
}

private function getSubNamespace(ClassBuilder $rootClass): string
Expand Down
8 changes: 8 additions & 0 deletions src/Symfony/Component/Config/Definition/ArrayNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,14 @@ public function setIgnoreExtraKeys(bool $boolean, bool $remove = true)
$this->removeExtraKeys = $this->ignoreExtraKeys && $remove;
}

/**
* Returns true when extra keys should be ignored without an exception.
*/
public function shouldIgnoreExtraKeys(): bool
{
return $this->ignoreExtraKeys;
}

/**
* {@inheritdoc}
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
'Foo\\MyArrayMessage' => [
'senders' => ['workqueue'],
],
]
],
]);
$config->messenger()
->routing('Foo\\Message')->senders(['workqueue']);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,17 @@
'sources' => [
'\\Acme\\Foo' => 'yellow',
'\\Acme\\Bar' => 'green',
]
],
],
'messenger' => [
'routing' => [
'Foo\\MyArrayMessage'=> ['senders'=>['workqueue']],
'Foo\\Message'=> ['senders'=>['workqueue']],
'Foo\\DoubleMessage' => ['senders'=>['sync', 'workqueue']],
'Foo\\MyArrayMessage' => ['senders' => ['workqueue']],
'Foo\\Message' => ['senders' => ['workqueue']],
'Foo\\DoubleMessage' => ['senders' => ['sync', 'workqueue']],
],
'receiving' => [
['priority'=>10, 'color'=>'blue'],
['priority'=>5, 'color'=>'red'],
]
['priority' => 10, 'color' => 'blue'],
['priority' => 5, 'color' => 'red'],
],
],
];
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Translation\Translator;

class AddToList implements ConfigurationInterface
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

use Symfony\Config\ArrayExtraKeysConfig;

return static function (ArrayExtraKeysConfig $config) {
$config->foo([
'extra1' => 'foo_extra1',
])
->baz('foo_baz')
->qux('foo_qux')
->set('extra2', 'foo_extra2')
->set('extra3', 'foo_extra3');

$config->bar([
'extra1' => 'bar1_extra1',
])
->corge('bar1_corge')
->grault('bar1_grault')
->set('extra2', 'bar1_extra2')
->set('extra3', 'bar1_extra3');

$config->bar([
'extra1' => 'bar2_extra1',
'extra4' => 'bar2_extra4',
])
->corge('bar2_corge')
->grault('bar2_grault')
->set('extra2', 'bar2_extra2')
->set('extra3', 'bar2_extra3')
->set('extra4', null);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

return [
'foo' => [
'baz' => 'foo_baz',
'qux' => 'foo_qux',
'extra1' => 'foo_extra1',
'extra2' => 'foo_extra2',
'extra3' => 'foo_extra3',
],
'bar' => [
[
'corge' => 'bar1_corge',
'grault' => 'bar1_grault',
'extra1' => 'bar1_extra1',
'extra2' => 'bar1_extra2',
'extra3' => 'bar1_extra3',
],
[
'corge' => 'bar2_corge',
'grault' => 'bar2_grault',
'extra1' => 'bar2_extra1',
'extra2' => 'bar2_extra2',
'extra3' => 'bar2_extra3',
],
],
];
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

namespace Symfony\Component\Config\Tests\Builder\Fixtures;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class ArrayExtraKeys implements ConfigurationInterface
{
public function getConfigTreeBuilder(): TreeBuilder
{
$tb = new TreeBuilder('array_extra_keys');
$rootNode = $tb->getRootNode();
$rootNode
->children()
->arrayNode('foo')
->ignoreExtraKeys(false)
->children()
->scalarNode('baz')->end()
->scalarNode('qux')->end()
->end()
->end()
->arrayNode('bar')
->prototype('array')
->ignoreExtraKeys(false)
->children()
->scalarNode('corge')->end()
->scalarNode('grault')->end()
->end()
->end()
->end()
;

return $tb;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
use Symfony\Config\NodeInitialValuesConfig;

return static function (NodeInitialValuesConfig $config) {
$config->someCleverName(['second'=>'foo'])->first('bar');
$config->someCleverName(['second' => 'foo'])->first('bar');
$config->messenger()
->transports('fast_queue', ['dsn'=>'sync://'])
->transports('fast_queue', ['dsn' => 'sync://'])
->serializer('acme');

$config->messenger()
->transports('slow_queue')
->dsn('doctrine://')
->options(['table'=>'my_messages']);
->options(['table' => 'my_messages']);
};
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@
'messenger' => [
'transports' => [
'fast_queue' => [
'dsn'=>'sync://',
'serializer'=>'acme',
'dsn' => 'sync://',
'serializer' => 'acme',
],
'slow_queue' => [
'dsn'=>'doctrine://',
'options'=>['table'=>'my_messages'],
]
]
]
'dsn' => 'doctrine://',
'options' => ['table' => 'my_messages'],
],
],
],
];
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Translation\Translator;

class NodeInitialValues implements ConfigurationInterface
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Symfony\Config\PlaceholdersConfig;

return static function (PlaceholdersConfig $config) {
Expand Down
10 changes: 10 additions & 0 deletions src/Symfony/Component/Config/Tests/Builder/GeneratedConfigTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public function fixtureNames()
'VariableType' => 'variable_type',
'AddToList' => 'add_to_list',
'NodeInitialValues' => 'node_initial_values',
'ArrayExtraKeys' => 'array_extra_keys',
];

foreach ($array as $name => $alias) {
Expand Down Expand Up @@ -105,6 +106,15 @@ public function testWrongInitialValues()
$configBuilder->someCleverName(['not_exists' => 'foo']);
}

public function testSetExtraKeyMethodIsNotGeneratedWhenAllowExtraKeysIsFalse()
{
/** @var AddToListConfig $configBuilder */
$configBuilder = $this->generateConfigBuilder(AddToList::class);

$this->assertFalse(method_exists($configBuilder->translator(), 'set'));
$this->assertFalse(method_exists($configBuilder->messenger()->receiving(), 'set'));
}

/**
* Generate the ConfigBuilder or return an already generated instance.
*/
Expand Down