1<?php 2 3/* 4 * This file is part of the Symfony package. 5 * 6 * (c) Fabien Potencier <fabien@symfony.com> 7 * 8 * For the full copyright and license information, please view the LICENSE 9 * file that was distributed with this source code. 10 */ 11 12namespace Symfony\Component\Console\Helper; 13 14use Symfony\Component\Console\Command\Command; 15use Symfony\Component\Console\Exception\InvalidArgumentException; 16 17/** 18 * HelperSet represents a set of helpers to be used with a command. 19 * 20 * @author Fabien Potencier <fabien@symfony.com> 21 */ 22class HelperSet implements \IteratorAggregate 23{ 24 /** 25 * @var Helper[] 26 */ 27 private $helpers = []; 28 private $command; 29 30 /** 31 * @param Helper[] $helpers An array of helper 32 */ 33 public function __construct(array $helpers = []) 34 { 35 foreach ($helpers as $alias => $helper) { 36 $this->set($helper, \is_int($alias) ? null : $alias); 37 } 38 } 39 40 public function set(HelperInterface $helper, string $alias = null) 41 { 42 $this->helpers[$helper->getName()] = $helper; 43 if (null !== $alias) { 44 $this->helpers[$alias] = $helper; 45 } 46 47 $helper->setHelperSet($this); 48 } 49 50 /** 51 * Returns true if the helper if defined. 52 * 53 * @return bool true if the helper is defined, false otherwise 54 */ 55 public function has(string $name) 56 { 57 return isset($this->helpers[$name]); 58 } 59 60 /** 61 * Gets a helper value. 62 * 63 * @return HelperInterface The helper instance 64 * 65 * @throws InvalidArgumentException if the helper is not defined 66 */ 67 public function get(string $name) 68 { 69 if (!$this->has($name)) { 70 throw new InvalidArgumentException(sprintf('The helper "%s" is not defined.', $name)); 71 } 72 73 return $this->helpers[$name]; 74 } 75 76 public function setCommand(Command $command = null) 77 { 78 $this->command = $command; 79 } 80 81 /** 82 * Gets the command associated with this helper set. 83 * 84 * @return Command A Command instance 85 */ 86 public function getCommand() 87 { 88 return $this->command; 89 } 90 91 /** 92 * @return Helper[] 93 */ 94 public function getIterator() 95 { 96 return new \ArrayIterator($this->helpers); 97 } 98} 99