Skip to content

[Config] Allow scalar configuration in PHP Configuration #46328

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 2 commits into from
May 17, 2022
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
8 changes: 3 additions & 5 deletions src/Symfony/Component/Config/Builder/ClassBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public function build(): string
}
$require .= sprintf('require_once __DIR__.\DIRECTORY_SEPARATOR.\'%s\';', implode('\'.\DIRECTORY_SEPARATOR.\'', $path))."\n";
}
$use = '';
$use = $require ? "\n" : '';
foreach (array_keys($this->use) as $statement) {
$use .= sprintf('use %s;', $statement)."\n";
}
Expand All @@ -81,17 +81,15 @@ public function build(): string
foreach ($this->methods as $method) {
$lines = explode("\n", $method->getContent());
foreach ($lines as $line) {
$body .= ' '.$line."\n";
$body .= ($line ? ' '.$line : '')."\n";
}
}

$content = strtr('<?php

namespace NAMESPACE;

REQUIRE
USE

REQUIREUSE
/**
* This class is automatically generated to help in creating a config.
*/
Expand Down
129 changes: 110 additions & 19 deletions src/Symfony/Component/Config/Builder/ConfigBuilderGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -136,14 +136,39 @@ private function handleArrayNode(ArrayNode $node, ClassBuilder $class, string $n
$class->addRequire($childClass);
$this->classes[] = $childClass;

$property = $class->addProperty($node->getName(), $childClass->getFqcn());
$body = '
$hasNormalizationClosures = $this->hasNormalizationClosures($node);
$property = $class->addProperty(
$node->getName(),
$this->getType($childClass->getFqcn(), $hasNormalizationClosures)
);
$body = $hasNormalizationClosures ? '
/**
* @return CLASS|$this
*/
public function NAME($value = [])
{
if (!\is_array($value)) {
$this->_usedProperties[\'PROPERTY\'] = true;
$this->PROPERTY = $value;

return $this;
}

if (!$this->PROPERTY instanceof CLASS) {
$this->_usedProperties[\'PROPERTY\'] = true;
$this->PROPERTY = new CLASS($value);
} elseif (0 < \func_num_args()) {
throw new InvalidConfigurationException(\'The node created by "NAME()" has already been initialized. You cannot pass values the second time you call NAME().\');
}

return $this->PROPERTY;
}' : '
public function NAME(array $value = []): CLASS
{
if (null === $this->PROPERTY) {
$this->_usedProperties[\'PROPERTY\'] = true;
$this->PROPERTY = new CLASS($value);
} elseif ([] !== $value) {
} elseif (0 < \func_num_args()) {
throw new InvalidConfigurationException(\'The node created by "NAME()" has already been initialized. You cannot pass values the second time you call NAME().\');
}

Expand Down Expand Up @@ -227,10 +252,29 @@ public function NAME(string $VAR, $VALUE): self
}
$class->addRequire($childClass);
$this->classes[] = $childClass;
$property = $class->addProperty($node->getName(), $childClass->getFqcn().'[]');

$hasNormalizationClosures = $this->hasNormalizationClosures($node) || $this->hasNormalizationClosures($prototype);
$property = $class->addProperty(
$node->getName(),
$this->getType($childClass->getFqcn().'[]', $hasNormalizationClosures)
);

if (null === $key = $node->getKeyAttribute()) {
$body = '
$body = $hasNormalizationClosures ? '
/**
* @return CLASS|$this
*/
public function NAME($value = [])
{
$this->_usedProperties[\'PROPERTY\'] = true;
if (!\is_array($value)) {
$this->PROPERTY[] = $value;

return $this;
}

return $this->PROPERTY[] = new CLASS($value);
}' : '
public function NAME(array $value = []): CLASS
{
$this->_usedProperties[\'PROPERTY\'] = true;
Expand All @@ -239,19 +283,38 @@ public function NAME(array $value = []): CLASS
}';
$class->addMethod($methodName, $body, ['PROPERTY' => $property->getName(), 'CLASS' => $childClass->getFqcn()]);
} else {
$body = '
public function NAME(string $VAR, array $VALUE = []): CLASS
$body = $hasNormalizationClosures ? '
/**
* @return CLASS|$this
*/
public function NAME(string $VAR, $VALUE = [])
{
if (!isset($this->PROPERTY[$VAR])) {
if (!\is_array($VALUE)) {
$this->_usedProperties[\'PROPERTY\'] = true;
$this->PROPERTY[$VAR] = $VALUE;

return $this->PROPERTY[$VAR] = new CLASS($VALUE);
return $this;
}
if ([] === $VALUE) {
return $this->PROPERTY[$VAR];

if (!isset($this->PROPERTY[$VAR]) || !$this->PROPERTY[$VAR] instanceof CLASS) {
$this->_usedProperties[\'PROPERTY\'] = true;
$this->PROPERTY[$VAR] = new CLASS($VALUE);
} elseif (1 < \func_num_args()) {
throw new InvalidConfigurationException(\'The node created by "NAME()" has already been initialized. You cannot pass values the second time you call NAME().\');
}

throw new InvalidConfigurationException(\'The node created by "NAME()" has already been initialized. You cannot pass values the second time you call NAME().\');
return $this->PROPERTY[$VAR];
}' : '
public function NAME(string $VAR, array $VALUE = []): CLASS
{
if (!isset($this->PROPERTY[$VAR])) {
$this->_usedProperties[\'PROPERTY\'] = true;
$this->PROPERTY[$VAR] = new CLASS($VALUE);
} elseif (1 < \func_num_args()) {
throw new InvalidConfigurationException(\'The node created by "NAME()" has already been initialized. You cannot pass values the second time you call NAME().\');
}

return $this->PROPERTY[$VAR];
}';
$class->addUse(InvalidConfigurationException::class);
$class->addMethod($methodName, $body, ['PROPERTY' => $property->getName(), 'CLASS' => $childClass->getFqcn(), 'VAR' => '' === $key ? 'key' : $key, 'VALUE' => 'value' === $key ? 'data' : 'value']);
Expand Down Expand Up @@ -375,16 +438,22 @@ private function buildToArray(ClassBuilder $class): void
$code = '$this->PROPERTY';
if (null !== $p->getType()) {
if ($p->isArray()) {
$code = 'array_map(function ($v) { return $v->toArray(); }, $this->PROPERTY)';
$code = $p->areScalarsAllowed()
? 'array_map(function ($v) { return $v instanceof CLASS ? $v->toArray() : $v; }, $this->PROPERTY)'
: 'array_map(function ($v) { return $v->toArray(); }, $this->PROPERTY)'
;
} else {
$code = '$this->PROPERTY->toArray()';
$code = $p->areScalarsAllowed()
? '$this->PROPERTY instanceof CLASS ? $this->PROPERTY->toArray() : $this->PROPERTY'
: '$this->PROPERTY->toArray()'
;
}
}

$body .= strtr('
if (isset($this->_usedProperties[\'PROPERTY\'])) {
$output[\'ORG_NAME\'] = '.$code.';
}', ['PROPERTY' => $p->getName(), 'ORG_NAME' => $p->getOriginalName()]);
}', ['PROPERTY' => $p->getName(), 'ORG_NAME' => $p->getOriginalName(), 'CLASS' => $p->getType()]);
}

$extraKeys = $class->shouldAllowExtraKeys() ? ' + $this->_extraKeys' : '';
Expand All @@ -405,9 +474,15 @@ private function buildConstructor(ClassBuilder $class): void
$code = '$value[\'ORG_NAME\']';
if (null !== $p->getType()) {
if ($p->isArray()) {
$code = 'array_map(function ($v) { return new '.$p->getType().'($v); }, $value[\'ORG_NAME\'])';
$code = $p->areScalarsAllowed()
? 'array_map(function ($v) { return \is_array($v) ? new '.$p->getType().'($v) : $v; }, $value[\'ORG_NAME\'])'
: 'array_map(function ($v) { return new '.$p->getType().'($v); }, $value[\'ORG_NAME\'])'
;
} else {
$code = 'new '.$p->getType().'($value[\'ORG_NAME\'])';
$code = $p->areScalarsAllowed()
? '\is_array($value[\'ORG_NAME\']) ? new '.$p->getType().'($value[\'ORG_NAME\']) : $value[\'ORG_NAME\']'
: 'new '.$p->getType().'($value[\'ORG_NAME\'])'
;
}
}

Expand Down Expand Up @@ -435,8 +510,7 @@ private function buildConstructor(ClassBuilder $class): void

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

Expand Down Expand Up @@ -467,4 +541,21 @@ private function getSubNamespace(ClassBuilder $rootClass): string
{
return sprintf('%s\\%s', $rootClass->getNamespace(), substr($rootClass->getName(), 0, -6));
}

private function hasNormalizationClosures(NodeInterface $node): bool
{
try {
$r = new \ReflectionProperty($node, 'normalizationClosures');
} catch (\ReflectionException $e) {
return false;
}
$r->setAccessible(true);

return [] !== $r->getValue($node);
}

private function getType(string $classType, bool $hasNormalizationClosures): string
{
return $classType.($hasNormalizationClosures ? '|scalar' : '');
}
}
11 changes: 11 additions & 0 deletions src/Symfony/Component/Config/Builder/Property.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class Property
private $name;
private $originalName;
private $array = false;
private $scalarsAllowed = false;
private $type = null;
private $content;

Expand All @@ -47,6 +48,11 @@ public function setType(string $type): void
$this->array = false;
$this->type = $type;

if ('|scalar' === substr($type, -7)) {
$this->scalarsAllowed = true;
$this->type = $type = substr($type, 0, -7);
}

if ('[]' === substr($type, -2)) {
$this->array = true;
$this->type = substr($type, 0, -2);
Expand All @@ -72,4 +78,9 @@ public function isArray(): bool
{
return $this->array;
}

public function areScalarsAllowed(): bool
{
return $this->scalarsAllowed;
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

use Symfony\Config\AddToListConfig;

return static function (AddToListConfig $config) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

return [
'translator' => [
'fallbacks' => ['sv', 'fr', 'es'],
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

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

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,9 @@

namespace Symfony\Config\AddToList\Messenger;


use Symfony\Component\Config\Loader\ParamConfigurator;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;


/**
* This class is automatically generated to help in creating a config.
*/
Expand All @@ -15,7 +13,7 @@ class ReceivingConfig
private $priority;
private $color;
private $_usedProperties = [];

/**
* @default null
* @param ParamConfigurator|int $value
Expand All @@ -25,10 +23,10 @@ public function priority($value): self
{
$this->_usedProperties['priority'] = true;
$this->priority = $value;

return $this;
}

/**
* @default null
* @param ParamConfigurator|mixed $value
Expand All @@ -38,30 +36,29 @@ public function color($value): self
{
$this->_usedProperties['color'] = true;
$this->color = $value;

return $this;
}

public function __construct(array $value = [])
{

if (array_key_exists('priority', $value)) {
$this->_usedProperties['priority'] = true;
$this->priority = $value['priority'];
unset($value['priority']);
}

if (array_key_exists('color', $value)) {
$this->_usedProperties['color'] = true;
$this->color = $value['color'];
unset($value['color']);
}

if ([] !== $value) {
throw new InvalidConfigurationException(sprintf('The following keys are not supported by "%s": ', __CLASS__).implode(', ', array_keys($value)));
}
}

public function toArray(): array
{
$output = [];
Expand All @@ -71,7 +68,7 @@ public function toArray(): array
if (isset($this->_usedProperties['color'])) {
$output['color'] = $this->color;
}

return $output;
}

Expand Down
Loading