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