HelperSet.php 2.2 KB

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