Spaces:
Runtime error
Runtime error
File size: 20,459 Bytes
7a66774 | 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 | <?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\Definition\Builder;
use Symfony\Component\Config\Definition\ArrayNode;
use Symfony\Component\Config\Definition\Exception\InvalidDefinitionException;
use Symfony\Component\Config\Definition\NodeInterface;
use Symfony\Component\Config\Definition\PrototypedArrayNode;
/**
* This class provides a fluent interface for defining an array node.
*
* @template TParent of NodeParentInterface|null = null
*
* @extends NodeDefinition<TParent>
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class ArrayNodeDefinition extends NodeDefinition implements ParentNodeDefinitionInterface
{
protected bool $performDeepMerging = true;
protected bool $ignoreExtraKeys = false;
protected bool $removeExtraKeys = true;
/**
* @var NodeDefinition<$this>[]
*/
protected array $children = [];
/**
* @var NodeDefinition<$this>
*/
protected NodeDefinition $prototype;
protected bool $atLeastOne = false;
protected bool $allowNewKeys = true;
protected ?string $key = null;
protected bool $removeKeyItem = false;
protected bool $addDefaults = false;
protected int|string|array|false|null $addDefaultChildren = false;
/**
* @var NodeBuilder<static>
*/
protected NodeBuilder $nodeBuilder;
protected bool $normalizeKeys = true;
/**
* @var list<ExprBuilder::TYPE_*>|null
*/
protected ?array $allowedTypes = null;
/**
* @param TParent $parent
*/
public function __construct(?string $name, ?NodeParentInterface $parent = null)
{
parent::__construct($name, $parent);
$this->nullEquivalent = [];
$this->trueEquivalent = [];
}
/**
* @return $this
*/
public function defaultValue(mixed $value): static
{
$this->nullEquivalent = null === $value ? null : [];
return parent::defaultValue($value);
}
/**
* @param NodeBuilder<static> $builder
*/
public function setBuilder(NodeBuilder $builder): void
{
$this->nodeBuilder = $builder;
}
/**
* Allows alternative types and wraps them into arrays.
*
* @param list<ExprBuilder::TYPE_INT|ExprBuilder::TYPE_STRING|ExprBuilder::TYPE_BOOL|ExprBuilder::TYPE_NULL|ExprBuilder::TYPE_BACKED_ENUM> $allowedTypes
* @param string|null $key The key to wrap the value in
*
* @return $this
*/
public function acceptAndWrap(array $allowedTypes, ?string $key = null): static
{
$this->allowedTypes = $allowedTypes;
foreach ($allowedTypes as $type) {
$this->beforeNormalization()->ifTrue(match ($type) {
ExprBuilder::TYPE_INT => is_int(...),
ExprBuilder::TYPE_STRING => is_string(...),
ExprBuilder::TYPE_BOOL => is_bool(...),
ExprBuilder::TYPE_NULL => is_null(...),
ExprBuilder::TYPE_BACKED_ENUM => static fn ($v) => $v instanceof \BackedEnum,
})->then(static fn ($v) => [$key ?? 0 => $v]);
}
return $this;
}
/**
* @return NodeBuilder<static>
*/
public function children(): NodeBuilder
{
return $this->getNodeBuilder();
}
/**
* Sets a prototype for child nodes.
*
* @template T of 'array'|'variable'|'scalar'|'string'|'boolean'|'integer'|'float'|'enum'
*
* @param T $type
*
* @return (
* T is 'array' ? ArrayNodeDefinition<$this>
* : (T is 'variable' ? VariableNodeDefinition<$this>
* : (T is 'scalar' ? ScalarNodeDefinition<$this>
* : (T is 'string' ? StringNodeDefinition<$this>
* : (T is 'boolean' ? BooleanNodeDefinition<$this>
* : (T is 'integer' ? IntegerNodeDefinition<$this>
* : (T is 'float' ? FloatNodeDefinition<$this>
* : (T is 'enum' ? EnumNodeDefinition<$this>
* : NodeDefinition<$this>)))))))
* )
*/
public function prototype(string $type): NodeDefinition
{
return $this->prototype = $this->getNodeBuilder()->node(null, $type)->setParent($this);
}
/**
* @return VariableNodeDefinition<$this>
*/
public function variablePrototype(): VariableNodeDefinition
{
return $this->prototype('variable');
}
/**
* @return ScalarNodeDefinition<$this>
*/
public function scalarPrototype(): ScalarNodeDefinition
{
return $this->prototype('scalar');
}
/**
* @return StringNodeDefinition<$this>
*/
public function stringPrototype(): StringNodeDefinition
{
return $this->prototype('string');
}
/**
* @return BooleanNodeDefinition<$this>
*/
public function booleanPrototype(): BooleanNodeDefinition
{
return $this->prototype('boolean');
}
/**
* @return IntegerNodeDefinition<$this>
*/
public function integerPrototype(): IntegerNodeDefinition
{
return $this->prototype('integer');
}
/**
* @return FloatNodeDefinition<$this>
*/
public function floatPrototype(): FloatNodeDefinition
{
return $this->prototype('float');
}
/**
* @return self<$this>
*/
public function arrayPrototype(): self
{
return $this->prototype('array');
}
/**
* @return EnumNodeDefinition<$this>
*/
public function enumPrototype(): EnumNodeDefinition
{
return $this->prototype('enum');
}
/**
* Adds the default value if the node is not set in the configuration.
*
* This method is applicable to concrete nodes only (not to prototype nodes).
* If this function has been called and the node is not set during the finalization
* phase, it's default value will be derived from its children default values.
*
* @return $this
*/
public function addDefaultsIfNotSet(): static
{
$this->addDefaults = true;
return $this;
}
/**
* Adds children with a default value when none are defined.
*
* This method is applicable to prototype nodes only.
*
* @param int|string|array|null $children The number of children|The child name|The children names to be added
*
* @return $this
*/
public function addDefaultChildrenIfNoneSet(int|string|array|null $children = null): static
{
$this->addDefaultChildren = $children;
return $this;
}
/**
* Requires the node to have at least one element.
*
* This method is applicable to prototype nodes only.
*
* @return $this
*/
public function requiresAtLeastOneElement(): static
{
$this->atLeastOne = true;
return $this;
}
/**
* Disallows adding news keys in a subsequent configuration.
*
* If used all keys have to be defined in the same configuration file.
*
* @return $this
*/
public function disallowNewKeysInSubsequentConfigs(): static
{
$this->allowNewKeys = false;
return $this;
}
/**
* Sets a normalization rule for XML configurations.
*
* @param string $singular The key to remap
* @param string|null $plural The plural of the key for irregular plurals
*
* @return $this
*/
public function fixXmlConfig(string $singular, ?string $plural = null): static
{
$this->normalization()->remap($singular, $plural);
return $this;
}
/**
* Sets the attribute which value is to be used as key.
*
* This is useful when you have an indexed array that should be an
* associative array. You can select an item from within the array
* to be the key of the particular item. For example, if "id" is the
* "key", then:
*
* [
* ['id' => 'my_name', 'foo' => 'bar'],
* ];
*
* becomes
*
* [
* 'my_name' => ['foo' => 'bar'],
* ];
*
* If you'd like "'id' => 'my_name'" to still be present in the resulting
* array, then you can set the second argument of this method to false.
*
* This method is applicable to prototype nodes only.
*
* @param string $name The name of the key
* @param bool $removeKeyItem Whether or not the key item should be removed
*
* @return $this
*/
public function useAttributeAsKey(string $name, bool $removeKeyItem = true): static
{
$this->key = $name;
$this->removeKeyItem = $removeKeyItem;
return $this;
}
/**
* Sets whether the node can be unset.
*
* @return $this
*/
public function canBeUnset(bool $allow = true): static
{
$this->merge()->allowUnset($allow);
return $this;
}
/**
* Adds an "enabled" boolean to enable the current section.
*
* By default, the section is disabled. If any configuration is specified then
* the node will be automatically enabled:
*
* enableableArrayNode: {enabled: true, ...} # The config is enabled & default values get overridden
* enableableArrayNode: ~ # The config is enabled & use the default values
* enableableArrayNode: true # The config is enabled & use the default values
* enableableArrayNode: {other: value, ...} # The config is enabled & default values get overridden
* enableableArrayNode: {enabled: false, ...} # The config is disabled
* enableableArrayNode: false # The config is disabled
*
* @param string|null $info A description of what happens when the node is enabled or disabled
*
* @return $this
*/
public function canBeEnabled(/* ?string $info = null */): static
{
$disabledNode = $this
->attribute('auto_enable', true)
->addDefaultsIfNotSet()
->treatFalseLike(['enabled' => false])
->treatTrueLike(['enabled' => true])
->treatNullLike(['enabled' => true])
->beforeNormalization()
->ifArray()
->then(static function ($v) {
$v['enabled'] ??= true;
return $v;
})
->end()
->children()
->booleanNode('enabled')
->defaultFalse()
;
$info = 1 <= \func_num_args() ? func_get_arg(0) : null;
if ($info) {
$disabledNode->info($info);
}
return $this;
}
/**
* Adds an "enabled" boolean to enable the current section.
*
* By default, the section is enabled.
*
* @param string|null $info A description of what happens when the node is enabled or disabled
*
* @return $this
*/
public function canBeDisabled(/* ?string $info = null */): static
{
$enabledNode = $this
->attribute('auto_enable', true)
->addDefaultsIfNotSet()
->treatFalseLike(['enabled' => false])
->treatTrueLike(['enabled' => true])
->treatNullLike(['enabled' => true])
->children()
->booleanNode('enabled')
->defaultTrue()
;
$info = 1 <= \func_num_args() ? func_get_arg(0) : null;
if ($info) {
$enabledNode->info($info);
}
return $this;
}
/**
* Disables the deep merging of the node.
*
* @return $this
*/
public function performNoDeepMerging(): static
{
$this->performDeepMerging = false;
return $this;
}
/**
* Allows extra config keys to be specified under an array without
* throwing an exception.
*
* Those config values are ignored and removed from the resulting
* array. This should be used only in special cases where you want
* to send an entire configuration array through a special tree that
* processes only part of the array.
*
* @param bool $remove Whether to remove the extra keys
*
* @return $this
*/
public function ignoreExtraKeys(bool $remove = true): static
{
$this->ignoreExtraKeys = true;
$this->removeExtraKeys = $remove;
return $this;
}
/**
* Sets whether to enable key normalization.
*
* @return $this
*/
public function normalizeKeys(bool $bool): static
{
$this->normalizeKeys = $bool;
return $this;
}
public function append(NodeDefinition $node): static
{
$this->children[$node->name ?? ''] = $node->setParent($this);
return $this;
}
/**
* Returns a node builder to be used to add children and prototype.
*
* @return NodeBuilder<static>
*/
protected function getNodeBuilder(): NodeBuilder
{
$this->nodeBuilder ??= new NodeBuilder();
return $this->nodeBuilder->setParent($this);
}
protected function createNode(): NodeInterface
{
if (!isset($this->prototype)) {
$node = new ArrayNode($this->name, $this->parent, $this->pathSeparator);
$this->validateConcreteNode($node);
$node->setAddIfNotSet($this->addDefaults);
foreach ($this->children as $child) {
$child->parent = $node;
$node->addChild($child->getNode());
}
} else {
$node = new PrototypedArrayNode($this->name, $this->parent, $this->pathSeparator);
$this->validatePrototypeNode($node);
if (null !== $this->key) {
$node->setKeyAttribute($this->key, $this->removeKeyItem);
}
if (true === $this->atLeastOne || false === $this->allowEmptyValue) {
$node->setMinNumberOfElements(1);
}
if ($this->default) {
if (null === $this->defaultValue) {
$node->setNullAsDefault();
} elseif (!\is_array($this->defaultValue)) {
throw new \InvalidArgumentException(\sprintf('%s: the default value of an array node has to be an array or null.', $node->getPath()));
} else {
$node->setDefaultValue($this->defaultValue);
}
}
if (false !== $this->addDefaultChildren) {
$node->setAddChildrenIfNoneSet($this->addDefaultChildren);
if ($this->prototype instanceof self && !isset($this->prototype->prototype)) {
$this->prototype->addDefaultsIfNotSet();
}
}
$this->prototype->parent = $node;
$node->setPrototype($this->prototype->getNode());
}
$node->setAllowNewKeys($this->allowNewKeys);
$node->addEquivalentValue(null, $this->nullEquivalent);
$node->addEquivalentValue(true, $this->trueEquivalent);
$node->addEquivalentValue(false, $this->falseEquivalent);
$node->setPerformDeepMerging($this->performDeepMerging);
$node->setRequired($this->required);
$node->setIgnoreExtraKeys($this->ignoreExtraKeys, $this->removeExtraKeys);
$node->setNormalizeKeys($this->normalizeKeys);
if ($this->deprecation) {
$node->setDeprecated($this->deprecation['package'], $this->deprecation['version'], $this->deprecation['message']);
}
$normalizedTypes = $this->allowedTypes ?? [];
if (isset($this->normalization)) {
$normalizedTypes = $normalizedTypes ?: $this->normalization->declaredTypes;
$node->setNormalizationClosures($this->normalization->before);
$node->setXmlRemappings($this->normalization->remappings);
}
$normalizedTypes[] = ExprBuilder::TYPE_ARRAY;
foreach ([$this->trueEquivalent, $this->falseEquivalent] as $equivalent) {
if (\is_array($equivalent) && $equivalent) {
$normalizedTypes[] = ExprBuilder::TYPE_BOOL;
}
}
$node->setNormalizedTypes(array_values(array_unique($normalizedTypes)));
if (isset($this->merge)) {
$node->setAllowOverwrite($this->merge->allowOverwrite);
$node->setAllowFalse($this->merge->allowFalse);
}
if (isset($this->validation)) {
$node->setFinalValidationClosures($this->validation->rules);
}
return $node;
}
/**
* Validate the configuration of a concrete node.
*
* @throws InvalidDefinitionException
*/
protected function validateConcreteNode(ArrayNode $node): void
{
$path = $node->getPath();
if (null !== $this->key) {
throw new InvalidDefinitionException(\sprintf('->useAttributeAsKey() is not applicable to concrete nodes at path "%s".', $path));
}
if (false === $this->allowEmptyValue) {
throw new InvalidDefinitionException(\sprintf('->cannotBeEmpty() is not applicable to concrete nodes at path "%s".', $path));
}
if (true === $this->atLeastOne) {
throw new InvalidDefinitionException(\sprintf('->requiresAtLeastOneElement() is not applicable to concrete nodes at path "%s".', $path));
}
if ($this->default) {
throw new InvalidDefinitionException(\sprintf('->defaultValue() is not applicable to concrete nodes at path "%s".', $path));
}
if (false !== $this->addDefaultChildren) {
throw new InvalidDefinitionException(\sprintf('->addDefaultChildrenIfNoneSet() is not applicable to concrete nodes at path "%s".', $path));
}
}
/**
* Validate the configuration of a prototype node.
*
* @throws InvalidDefinitionException
*/
protected function validatePrototypeNode(PrototypedArrayNode $node): void
{
$path = $node->getPath();
if ($this->addDefaults) {
throw new InvalidDefinitionException(\sprintf('->addDefaultsIfNotSet() is not applicable to prototype nodes at path "%s".', $path));
}
if (false !== $this->addDefaultChildren) {
if ($this->default) {
throw new InvalidDefinitionException(\sprintf('A default value and default children might not be used together at path "%s".', $path));
}
if (null !== $this->key && (null === $this->addDefaultChildren || \is_int($this->addDefaultChildren) && $this->addDefaultChildren > 0)) {
throw new InvalidDefinitionException(\sprintf('->addDefaultChildrenIfNoneSet() should set default children names as ->useAttributeAsKey() is used at path "%s".', $path));
}
if (null === $this->key && (\is_string($this->addDefaultChildren) || \is_array($this->addDefaultChildren))) {
throw new InvalidDefinitionException(\sprintf('->addDefaultChildrenIfNoneSet() might not set default children names as ->useAttributeAsKey() is not used at path "%s".', $path));
}
}
}
/**
* @return NodeDefinition<$this>[]
*/
public function getChildNodeDefinitions(): array
{
return $this->children;
}
/**
* Finds a node defined by the given $nodePath.
*
* @param string $nodePath The path of the node to find. e.g "doctrine.orm.mappings"
*/
public function find(string $nodePath): NodeDefinition
{
$firstPathSegment = (false === $pathSeparatorPos = strpos($nodePath, $this->pathSeparator))
? $nodePath
: substr($nodePath, 0, $pathSeparatorPos);
if (null === $node = ($this->children[$firstPathSegment] ?? null)) {
throw new \RuntimeException(\sprintf('Node with name "%s" does not exist in the current node "%s".', $firstPathSegment, $this->name));
}
if (false === $pathSeparatorPos) {
return $node;
}
return $node->find(substr($nodePath, $pathSeparatorPos + \strlen($this->pathSeparator)));
}
}
|