Description
Problem
If a command contains a call to $this->getHelper('helper')
and there is no helperSet defined, the expected InvalidArgumentException
(that should be thrown if the helper is not defined) is not thrown because of a PHP fatal error.
The error can be reproduced when testing a command with the CommandTester
.
If the command contains $this->getHelper('question')
and is executed without calling Command#setHelperSet(new HelperSet())
, it causes:
PHP Fatal error: Call to a member function get() on null in /project/vendor/symfony/console/Command/Command.php on line 609
It's a bit hard to debug because the error only say where the get()
is called, so there is no real trace containing the original method call.
Possible solution
My first thought, throw an exception in Command#getHelper()
if there is no helperSet defined.
I have a ready patch:
use Symfony\Component\Console\Exception\LogicException;
// ...
/**
* Gets a helper instance by name.
*
* @param string $name The helper name
*
* @return mixed The helper value
*
* @throws LogicException If there is no helperSet defined
* @throws InvalidArgumentException if the helper is not defined
*/
public function getHelper($name)
{
if (null === $this->helperSet) {
throw new LogicException(sprintf('Unable to retrieve the helper "%s" because there is no HelperSet defined. Did you forget to call %s#setHelperSet()?', $name, get_class($this)));
}
return $this->helperSet->get($name);
}
That gives:
Symfony\Component\Console\Exception\LogicException: Unable to retrieve the helper "question" because there is no HelperSet defined. Did you forget to call Command\MyCommand#setHelperSet()?
Otherwise, we could define an HelperSet
by default and so the InvalidArgumentException
would be thrown.
Am I wrong when I think that this error should be prevented?
Or is there a better idea?
Thank's.