Skip to content

Commit

Permalink
Add helper method to shell class for loading/fetching helper instances
Browse files Browse the repository at this point in the history
  • Loading branch information
Gareth Ellis committed Dec 1, 2015
1 parent 2854940 commit 53b9dc8
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
30 changes: 30 additions & 0 deletions lib/Cake/Console/Shell.php
Expand Up @@ -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.
*
Expand Down Expand Up @@ -779,6 +786,29 @@ public function createFile($path, $contents) {
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
*
Expand Down
22 changes: 22 additions & 0 deletions lib/Cake/Test/Case/Console/ShellTest.php
Expand Up @@ -21,6 +21,7 @@
App::uses('ShellDispatcher', 'Console');
App::uses('Shell', 'Console');
App::uses('Folder', 'Utility');
App::uses("ProgressHelper", "Console/Helper");

/**
* ShellTestShell class
Expand Down Expand Up @@ -975,4 +976,25 @@ public function testQuietLog() {
$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");
}

}

0 comments on commit 53b9dc8

Please sign in to comment.