HelperSet.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 $helpers = [];
  23. /**
  24. * @param HelperInterface[] $helpers
  25. */
  26. public function __construct($helpers = [])
  27. {
  28. foreach ($helpers as $alias => $helper) {
  29. $this->set($helper, \is_int($alias) ? null : $alias);
  30. }
  31. }
  32. /**
  33. * @return void
  34. * @param \Symfony\Component\Console\Helper\HelperInterface $helper
  35. * @param string|null $alias
  36. */
  37. public function set($helper, $alias = null)
  38. {
  39. $this->helpers[$helper->getName()] = $helper;
  40. if (null !== $alias) {
  41. $this->helpers[$alias] = $helper;
  42. }
  43. $helper->setHelperSet($this);
  44. }
  45. /**
  46. * Returns true if the helper if defined.
  47. * @param string $name
  48. */
  49. public function has($name)
  50. {
  51. return isset($this->helpers[$name]);
  52. }
  53. /**
  54. * Gets a helper value.
  55. *
  56. * @throws InvalidArgumentException if the helper is not defined
  57. * @param string $name
  58. */
  59. public function get($name)
  60. {
  61. if (!$this->has($name)) {
  62. throw new InvalidArgumentException(sprintf('The helper "%s" is not defined.', $name));
  63. }
  64. return $this->helpers[$name];
  65. }
  66. public function getIterator()
  67. {
  68. return new \ArrayIterator($this->helpers);
  69. }
  70. }