HelperSet.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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\Console\Helper;
  11. use Symfony\Component\Console\Exception\InvalidArgumentException;
  12. /**
  13. * HelperSet represents a set of helpers to be used with a command.
  14. *
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. *
  17. * @implements \IteratorAggregate<string, HelperInterface>
  18. */
  19. class HelperSet implements \IteratorAggregate
  20. {
  21. /** @var array<string, HelperInterface> */
  22. private array $helpers = [];
  23. /**
  24. * @param HelperInterface[] $helpers
  25. */
  26. public function __construct(array $helpers = [])
  27. {
  28. foreach ($helpers as $alias => $helper) {
  29. $this->set($helper, \is_int($alias) ? null : $alias);
  30. }
  31. }
  32. /**
  33. * @return void
  34. */
  35. public function set(HelperInterface $helper, ?string $alias = null)
  36. {
  37. $this->helpers[$helper->getName()] = $helper;
  38. if (null !== $alias) {
  39. $this->helpers[$alias] = $helper;
  40. }
  41. $helper->setHelperSet($this);
  42. }
  43. /**
  44. * Returns true if the helper if defined.
  45. */
  46. public function has(string $name): bool
  47. {
  48. return isset($this->helpers[$name]);
  49. }
  50. /**
  51. * Gets a helper value.
  52. *
  53. * @throws InvalidArgumentException if the helper is not defined
  54. */
  55. public function get(string $name): HelperInterface
  56. {
  57. if (!$this->has($name)) {
  58. throw new InvalidArgumentException(sprintf('The helper "%s" is not defined.', $name));
  59. }
  60. return $this->helpers[$name];
  61. }
  62. public function getIterator(): \Traversable
  63. {
  64. return new \ArrayIterator($this->helpers);
  65. }
  66. }