HelperSet.php 2.4 KB

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