BindTrait.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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\Exception\InvalidArgumentException;
  12. use Symfony\Component\DependencyInjection\Reference;
  13. trait BindTrait
  14. {
  15. /**
  16. * Sets bindings.
  17. *
  18. * Bindings map $named or FQCN arguments to values that should be
  19. * injected in the matching parameters (of the constructor, of methods
  20. * called and of controller actions).
  21. *
  22. * @param string $nameOrFqcn A parameter name with its "$" prefix, or a FQCN
  23. * @param mixed $valueOrRef The value or reference to bind
  24. *
  25. * @return $this
  26. */
  27. final public function bind($nameOrFqcn, $valueOrRef)
  28. {
  29. $valueOrRef = static::processValue($valueOrRef, true);
  30. if (isset($nameOrFqcn[0]) && '$' !== $nameOrFqcn[0] && !$valueOrRef instanceof Reference) {
  31. 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));
  32. }
  33. $bindings = $this->definition->getBindings();
  34. $bindings[$nameOrFqcn] = $valueOrRef;
  35. $this->definition->setBindings($bindings);
  36. return $this;
  37. }
  38. }