ParentTrait.php 1.9 KB

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