HelperSet.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. public function set(HelperInterface $helper, ?string $alias = null): void
  33. {
  34. $this->helpers[$helper->getName()] = $helper;
  35. if (null !== $alias) {
  36. $this->helpers[$alias] = $helper;
  37. }
  38. $helper->setHelperSet($this);
  39. }
  40. /**
  41. * Returns true if the helper if defined.
  42. */
  43. public function has(string $name): bool
  44. {
  45. return isset($this->helpers[$name]);
  46. }
  47. /**
  48. * Gets a helper value.
  49. *
  50. * @throws InvalidArgumentException if the helper is not defined
  51. */
  52. public function get(string $name): HelperInterface
  53. {
  54. if (!$this->has($name)) {
  55. throw new InvalidArgumentException(\sprintf('The helper "%s" is not defined.', $name));
  56. }
  57. return $this->helpers[$name];
  58. }
  59. public function getIterator(): \Traversable
  60. {
  61. return new \ArrayIterator($this->helpers);
  62. }
  63. }