HelperSet.php 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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 = array();
  24. private $command;
  25. /**
  26. * @param Helper[] $helpers An array of helper
  27. */
  28. public function __construct(array $helpers = array())
  29. {
  30. foreach ($helpers as $alias => $helper) {
  31. $this->set($helper, is_int($alias) ? null : $alias);
  32. }
  33. }
  34. /**
  35. * Sets a helper.
  36. *
  37. * @param HelperInterface $helper The helper instance
  38. * @param string $alias An alias
  39. */
  40. public function set(HelperInterface $helper, $alias = null)
  41. {
  42. $this->helpers[$helper->getName()] = $helper;
  43. if (null !== $alias) {
  44. $this->helpers[$alias] = $helper;
  45. }
  46. $helper->setHelperSet($this);
  47. }
  48. /**
  49. * Returns true if the helper if defined.
  50. *
  51. * @param string $name The helper name
  52. *
  53. * @return bool true if the helper is defined, false otherwise
  54. */
  55. public function has($name)
  56. {
  57. return isset($this->helpers[$name]);
  58. }
  59. /**
  60. * Gets a helper value.
  61. *
  62. * @param string $name The helper name
  63. *
  64. * @return HelperInterface The helper instance
  65. *
  66. * @throws InvalidArgumentException if the helper is not defined
  67. */
  68. public function get($name)
  69. {
  70. if (!$this->has($name)) {
  71. throw new InvalidArgumentException(sprintf('The helper "%s" is not defined.', $name));
  72. }
  73. return $this->helpers[$name];
  74. }
  75. public function setCommand(Command $command = null)
  76. {
  77. $this->command = $command;
  78. }
  79. /**
  80. * Gets the command associated with this helper set.
  81. *
  82. * @return Command A Command instance
  83. */
  84. public function getCommand()
  85. {
  86. return $this->command;
  87. }
  88. /**
  89. * @return Helper[]
  90. */
  91. public function getIterator()
  92. {
  93. return new \ArrayIterator($this->helpers);
  94. }
  95. }