Add helper method to shell class for loading/fetching helper instances

This commit is contained in:
Gareth Ellis 2015-12-01 13:07:56 +00:00
parent 2854940693
commit 53b9dc83f6
2 changed files with 52 additions and 0 deletions

View file

@ -174,6 +174,13 @@ class Shell extends Object {
*/
protected $_lastWritten = 0;
/**
* Contains helpers which have been previously instantiated
*
* @var array
*/
protected $_helpers = array();
/**
* Constructs this Shell instance.
*
@ -779,6 +786,29 @@ class Shell extends Object {
return false;
}
/**
* Load given shell helper class
*
* @param string $name Name of the helper class. Supports plugin syntax.
* @return ShellHelper Instance of helper class
* @throws RunTimeException If invalid class name is provided
*/
public function helper($name)
{
list($plugin, $helperClassName) = pluginSplit($name, true);
$helperClassName = Inflector::camelize($name) . "ShellHelper";
if (isset($this->_helpers[$name])) {
return $this->_helpers[$name];
}
App::uses($helperClassName, $plugin . "Console/Helper");
if (!class_exists($helperClassName)) {
throw new RuntimeException("Class " . $helperClassName . " not found");
}
$helper = new $helperClassName($this->stdout);
$this->_helpers[$name] = $helper;
return $helper;
}
/**
* Action to create a Unit Test
*

View file

@ -21,6 +21,7 @@
App::uses('ShellDispatcher', 'Console');
App::uses('Shell', 'Console');
App::uses('Folder', 'Utility');
App::uses("ProgressHelper", "Console/Helper");
/**
* ShellTestShell class
@ -975,4 +976,25 @@ TEXT;
$this->Shell->runCommand('foo', array('--quiet'));
}
/**
* Test getting an instance of a helper
*
* @return void
*/
public function testGetInstanceOfHelper()
{
$actual = $this->Shell->helper("progress");
$this->assertInstanceOf("ProgressShellHelper", $actual);
}
/**
* Test getting an invalid helper
*
* @expectedException RunTimeException
*/
public function testGetInvalidHelper()
{
$this->Shell->helper("tomato");
}
}