BindTrait.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\DependencyInjection\Loader\Configurator\Traits;
  11. use Symfony\Component\DependencyInjection\Argument\BoundArgument;
  12. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  13. use Symfony\Component\DependencyInjection\Loader\Configurator\DefaultsConfigurator;
  14. use Symfony\Component\DependencyInjection\Loader\Configurator\InstanceofConfigurator;
  15. use Symfony\Component\DependencyInjection\Reference;
  16. trait BindTrait
  17. {
  18. /**
  19. * Sets bindings.
  20. *
  21. * Bindings map $named or FQCN arguments to values that should be
  22. * injected in the matching parameters (of the constructor, of methods
  23. * called and of controller actions).
  24. *
  25. * @param string $nameOrFqcn A parameter name with its "$" prefix, or an FQCN
  26. * @param mixed $valueOrRef The value or reference to bind
  27. *
  28. * @return $this
  29. */
  30. final public function bind(string $nameOrFqcn, $valueOrRef): self
  31. {
  32. $valueOrRef = static::processValue($valueOrRef, true);
  33. if (!preg_match('/^(?:(?:array|bool|float|int|string)[ \t]*+)?\$/', $nameOrFqcn) && !$valueOrRef instanceof Reference) {
  34. throw new InvalidArgumentException(sprintf('Invalid binding for service "%s": named arguments must start with a "$", and FQCN must map to references. Neither applies to binding "%s".', $this->id, $nameOrFqcn));
  35. }
  36. $bindings = $this->definition->getBindings();
  37. $type = $this instanceof DefaultsConfigurator ? BoundArgument::DEFAULTS_BINDING : ($this instanceof InstanceofConfigurator ? BoundArgument::INSTANCEOF_BINDING : BoundArgument::SERVICE_BINDING);
  38. $bindings[$nameOrFqcn] = new BoundArgument($valueOrRef, true, $type, $this->path ?? null);
  39. $this->definition->setBindings($bindings);
  40. return $this;
  41. }
  42. }