ParentTrait.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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\ChildDefinition;
  12. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  13. /**
  14. * @method $this parent(string $parent)
  15. */
  16. trait ParentTrait
  17. {
  18. /**
  19. * Sets the Definition to inherit from.
  20. *
  21. * @param string $parent
  22. *
  23. * @return $this
  24. *
  25. * @throws InvalidArgumentException when parent cannot be set
  26. */
  27. final protected function setParent($parent)
  28. {
  29. if (!$this->allowParent) {
  30. throw new InvalidArgumentException(sprintf('A parent cannot be defined when either "_instanceof" or "_defaults" are also defined for service prototype "%s".', $this->id));
  31. }
  32. if ($this->definition instanceof ChildDefinition) {
  33. $this->definition->setParent($parent);
  34. } elseif ($this->definition->isAutoconfigured()) {
  35. throw new InvalidArgumentException(sprintf('The service "%s" cannot have a "parent" and also have "autoconfigure". Try disabling autoconfiguration for the service.', $this->id));
  36. } elseif ($this->definition->getBindings()) {
  37. throw new InvalidArgumentException(sprintf('The service "%s" cannot have a "parent" and also "bind" arguments.', $this->id));
  38. } else {
  39. // cast Definition to ChildDefinition
  40. $definition = serialize($this->definition);
  41. $definition = substr_replace($definition, '53', 2, 2);
  42. $definition = substr_replace($definition, 'Child', 44, 0);
  43. $definition = unserialize($definition);
  44. $this->definition = $definition->setParent($parent);
  45. }
  46. return $this;
  47. }
  48. }