Skip to content

[DependencyInjection][FrameworkBundle] Introducing container non-empty parameters #57611

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
Sep 19, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,7 @@ public function load(array $configs, ContainerBuilder $container): void
if (isset($config['secret'])) {
$container->setParameter('kernel.secret', $config['secret']);
}
$container->nonEmptyParameter('kernel.secret', 'A non-empty value for the parameter "kernel.secret" is required. Did you forget to configure the "framework.secret" option?');

$container->setParameter('kernel.http_method_override', $config['http_method_override']);
$container->setParameter('kernel.trust_x_sendfile_type_header', $config['trust_x_sendfile_type_header']);
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Bundle/FrameworkBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
"ext-xml": "*",
"symfony/cache": "^6.4|^7.0",
"symfony/config": "^6.4|^7.0",
"symfony/dependency-injection": "^7.1.5",
"symfony/dependency-injection": "^7.2",
"symfony/deprecation-contracts": "^2.5|^3",
"symfony/error-handler": "^6.4|^7.0",
"symfony/event-dispatcher": "^6.4|^7.0",
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Component/DependencyInjection/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ CHANGELOG
* Deprecate `!tagged` tag, use `!tagged_iterator` instead
* Add a `ContainerBuilder::registerChild()` shortcut method for registering child definitions
* Add support for `key-type` in `XmlFileLoader`
* Enable non-empty parameters with `ParameterBag::nonEmpty()` and `ContainerBuilder::nonEmptyParameter()` methods

7.1
---
Expand Down
3 changes: 2 additions & 1 deletion src/Symfony/Component/DependencyInjection/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,8 @@ public function compile(): void

$this->parameterBag = new FrozenParameterBag(
$this->parameterBag->all(),
$this->parameterBag instanceof ParameterBag ? $this->parameterBag->allDeprecated() : []
$this->parameterBag instanceof ParameterBag ? $this->parameterBag->allDeprecated() : [],
$this->parameterBag instanceof ParameterBag ? $this->parameterBag->allNonEmpty() : [],
);

$this->compiled = true;
Expand Down
13 changes: 13 additions & 0 deletions src/Symfony/Component/DependencyInjection/ContainerBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -671,6 +671,10 @@ public function merge(self $container): void
foreach ($otherBag->allDeprecated() as $name => $deprecated) {
$parameterBag->deprecate($name, ...$deprecated);
}

foreach ($otherBag->allNonEmpty() as $name => $message) {
$parameterBag->nonEmpty($name, $message);
}
}

if ($this->trackResources) {
Expand Down Expand Up @@ -764,6 +768,15 @@ public function deprecateParameter(string $name, string $package, string $versio
$this->parameterBag->deprecate($name, $package, $version, $message);
}

public function nonEmptyParameter(string $name, string $message): void
{
if (!$this->parameterBag instanceof ParameterBag) {
throw new BadMethodCallException(\sprintf('The parameter bag must be an instance of "%s" to call "%s()".', ParameterBag::class, __METHOD__));
}

$this->parameterBag->nonEmpty($name, $message);
}

/**
* Compiles the container.
*
Expand Down
53 changes: 45 additions & 8 deletions src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -1258,13 +1258,17 @@ class $class extends $baseClass
{
private const DEPRECATED_PARAMETERS = [];

private const NONEMPTY_PARAMETERS = [];

protected \$parameters = [];

public function __construct()
{

EOF;
$code = str_replace(" private const DEPRECATED_PARAMETERS = [];\n\n", $this->addDeprecatedParameters(), $code);
$code = str_replace(" private const NONEMPTY_PARAMETERS = [];\n\n", $this->addNonEmptyParameters(), $code);

if ($this->asFiles) {
$code = str_replace('__construct()', '__construct(private array $buildParameters = [], protected string $containerDir = __DIR__)', $code);

Expand Down Expand Up @@ -1429,6 +1433,24 @@ private function addDeprecatedParameters(): string
return " private const DEPRECATED_PARAMETERS = [\n{$code} ];\n\n";
}

private function addNonEmptyParameters(): string
{
if (!($bag = $this->container->getParameterBag()) instanceof ParameterBag) {
return '';
}

if (!$nonEmpty = $bag->allNonEmpty()) {
return '';
}
$code = '';
ksort($nonEmpty);
foreach ($nonEmpty as $param => $message) {
$code .= ' '.$this->doExport($param).' => '.$this->doExport($message).",\n";
}

return " private const NONEMPTY_PARAMETERS = [\n{$code} ];\n\n";
}

private function addMethodMap(): string
{
$code = '';
Expand Down Expand Up @@ -1563,14 +1585,16 @@ private function addInlineRequires(bool $hasProxyClasses): string

private function addDefaultParametersMethod(): string
{
if (!$this->container->getParameterBag()->all()) {
$bag = $this->container->getParameterBag();

if (!$bag->all() && (!$bag instanceof ParameterBag || !$bag->allNonEmpty())) {
return '';
}

$php = [];
$dynamicPhp = [];

foreach ($this->container->getParameterBag()->all() as $key => $value) {
foreach ($bag->all() as $key => $value) {
if ($key !== $resolvedKey = $this->container->resolveEnvPlaceholders($key)) {
throw new InvalidArgumentException(\sprintf('Parameter name cannot use env parameters: "%s".', $resolvedKey));
}
Expand Down Expand Up @@ -1600,13 +1624,20 @@ public function getParameter(string $name): array|bool|string|int|float|\UnitEnu
}

if (!(isset($this->parameters[$name]) || isset($this->loadedDynamicParameters[$name]) || \array_key_exists($name, $this->parameters))) {
throw new ParameterNotFoundException($name);
throw new ParameterNotFoundException($name, extraMessage: self::NONEMPTY_PARAMETERS[$name] ?? null);
}

if (isset($this->loadedDynamicParameters[$name])) {
return $this->loadedDynamicParameters[$name] ? $this->dynamicParameters[$name] : $this->getDynamicParameter($name);
$value = $this->loadedDynamicParameters[$name] ? $this->dynamicParameters[$name] : $this->getDynamicParameter($name);
} else {
$value = $this->parameters[$name];
}

if (isset(self::NONEMPTY_PARAMETERS[$name]) && (null === $value || '' === $value || [] === $value)) {
throw new \Symfony\Component\DependencyInjection\Exception\EmptyParameterValueException(self::NONEMPTY_PARAMETERS[$name]);
}

return $this->parameters[$name];
return $value;
}

public function hasParameter(string $name): bool
Expand All @@ -1633,7 +1664,7 @@ public function getParameterBag(): ParameterBagInterface
foreach ($this->buildParameters as $name => $value) {
$parameters[$name] = $value;
}
$this->parameterBag = new FrozenParameterBag($parameters, self::DEPRECATED_PARAMETERS);
$this->parameterBag = new FrozenParameterBag($parameters, self::DEPRECATED_PARAMETERS, self::NONEMPTY_PARAMETERS);
}

return $this->parameterBag;
Expand All @@ -1645,9 +1676,15 @@ public function getParameterBag(): ParameterBagInterface
$code = preg_replace('/^.*buildParameters.*\n.*\n.*\n\n?/m', '', $code);
}

if (!($bag = $this->container->getParameterBag()) instanceof ParameterBag || !$bag->allDeprecated()) {
if (!$bag instanceof ParameterBag || !$bag->allDeprecated()) {
$code = preg_replace("/\n.*DEPRECATED_PARAMETERS.*\n.*\n.*\n/m", '', $code, 1);
$code = str_replace(', self::DEPRECATED_PARAMETERS', '', $code);
$code = str_replace(', self::DEPRECATED_PARAMETERS', ', []', $code);
}

if (!$bag instanceof ParameterBag || !$bag->allNonEmpty()) {
$code = str_replace(', extraMessage: self::NONEMPTY_PARAMETERS[$name] ?? null', '', $code);
$code = str_replace(', self::NONEMPTY_PARAMETERS', '', $code);
$code = preg_replace("/\n.*NONEMPTY_PARAMETERS.*\n.*\n.*\n/m", '', $code, 1);
}

if ($dynamicPhp) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?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\DependencyInjection\Exception;

use Psr\Container\NotFoundExceptionInterface;

/**
* This exception is thrown when an existent parameter with an empty value is used.
*
* @author Yonel Ceruto <open@yceruto.dev>
*/
class EmptyParameterValueException extends InvalidArgumentException implements NotFoundExceptionInterface
{
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ public function __construct(
private array $alternatives = [],
private ?string $nonNestedAlternative = null,
private ?string $sourceExtensionName = null,
private ?string $extraMessage = null,
) {
parent::__construct('', 0, $previous);

Expand All @@ -57,7 +58,7 @@ public function updateRepr(): void
}

if ($this->alternatives) {
if (1 == \count($this->alternatives)) {
if (1 === \count($this->alternatives)) {
$this->message .= ' Did you mean this: "';
} else {
$this->message .= ' Did you mean one of these: "';
Expand All @@ -66,6 +67,10 @@ public function updateRepr(): void
} elseif (null !== $this->nonNestedAlternative) {
$this->message .= ' You cannot access nested array items, do you want to inject "'.$this->nonNestedAlternative.'" instead?';
}

if ($this->extraMessage) {
$this->message .= ' '.$this->extraMessage;
}
}

public function getKey(): string
Expand Down Expand Up @@ -103,4 +108,16 @@ public function setSourceExtensionName(?string $sourceExtensionName): void

$this->updateRepr();
}

public function getExtraMessage(): ?string
{
return $this->extraMessage;
}

public function setExtraMessage(?string $extraMessage): void
{
$this->extraMessage = $extraMessage;

$this->updateRepr();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ class FrozenParameterBag extends ParameterBag
public function __construct(
array $parameters = [],
protected array $deprecatedParameters = [],
protected array $nonEmptyParameters = [],
) {
$this->parameters = $parameters;
$this->resolved = true;
Expand All @@ -54,6 +55,11 @@ public function deprecate(string $name, string $package, string $version, string
throw new LogicException('Impossible to call deprecate() on a frozen ParameterBag.');
}

public function nonEmpty(string $name, string $message = 'A non-empty parameter "%s" is required.'): never
{
throw new LogicException('Impossible to call nonEmpty() on a frozen ParameterBag.');
}

public function remove(string $name): never
{
throw new LogicException('Impossible to call remove() on a frozen ParameterBag.');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Symfony\Component\DependencyInjection\ParameterBag;

use Symfony\Component\DependencyInjection\Exception\EmptyParameterValueException;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;
Expand All @@ -26,6 +27,7 @@ class ParameterBag implements ParameterBagInterface
protected array $parameters = [];
protected bool $resolved = false;
protected array $deprecatedParameters = [];
protected array $nonEmptyParameters = [];

public function __construct(array $parameters = [])
{
Expand Down Expand Up @@ -54,13 +56,22 @@ public function allDeprecated(): array
return $this->deprecatedParameters;
}

public function allNonEmpty(): array
{
return $this->nonEmptyParameters;
}

public function get(string $name): array|bool|string|int|float|\UnitEnum|null
{
if (!\array_key_exists($name, $this->parameters)) {
if (!$name) {
throw new ParameterNotFoundException($name);
}

if (\array_key_exists($name, $this->nonEmptyParameters)) {
throw new ParameterNotFoundException($name, extraMessage: $this->nonEmptyParameters[$name]);
}

$alternatives = [];
foreach ($this->parameters as $key => $parameterValue) {
$lev = levenshtein($name, $key);
Expand Down Expand Up @@ -92,6 +103,10 @@ public function get(string $name): array|bool|string|int|float|\UnitEnum|null
trigger_deprecation(...$this->deprecatedParameters[$name]);
}

if (\array_key_exists($name, $this->nonEmptyParameters) && (null === $this->parameters[$name] || '' === $this->parameters[$name] || [] === $this->parameters[$name])) {
throw new EmptyParameterValueException($this->nonEmptyParameters[$name]);
}

return $this->parameters[$name];
}

Expand All @@ -118,14 +133,19 @@ public function deprecate(string $name, string $package, string $version, string
$this->deprecatedParameters[$name] = [$package, $version, $message, $name];
}

public function nonEmpty(string $name, string $message): void
{
$this->nonEmptyParameters[$name] = $message;
}

public function has(string $name): bool
{
return \array_key_exists($name, $this->parameters);
}

public function remove(string $name): void
{
unset($this->parameters[$name], $this->deprecatedParameters[$name]);
unset($this->parameters[$name], $this->deprecatedParameters[$name], $this->nonEmptyParameters[$name]);
}

public function resolve(): void
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -511,6 +511,27 @@ public function testDeprecatedParametersAsFiles()
$this->assertStringMatchesFormatFile(self::$fixturesPath.'/php/services_deprecated_parameters_as_files.txt', $dump);
}

public function testNonEmptyParameters()
{
$container = include self::$fixturesPath.'/containers/container_nonempty_parameters.php';
$container->compile();

$dumper = new PhpDumper($container);

$this->assertStringEqualsFile(self::$fixturesPath.'/php/services_nonempty_parameters.php', $dumper->dump());
}

public function testNonEmptyParametersAsFiles()
{
$container = include self::$fixturesPath.'/containers/container_nonempty_parameters.php';
$container->compile();

$dumper = new PhpDumper($container);
$dump = print_r($dumper->dump(['as_files' => true, 'file' => __DIR__, 'inline_factories_parameter' => false, 'inline_class_loader_parameter' => false]), true);

$this->assertStringMatchesFormatFile(self::$fixturesPath.'/php/services_nonempty_parameters_as_files.txt', $dump);
}

public function testEnvInId()
{
$container = include self::$fixturesPath.'/containers/container_env_in_id.php';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Parameter;

$container = new ContainerBuilder();
$container->nonEmptyParameter('bar', 'Did you forget to configure the "foo.bar" option?');
$container->register('foo', 'stdClass')
->setArguments([new Parameter('bar')])
->setPublic(true)
;

return $container;
Loading
Loading