From 53b9dc83f6dcc163e36aabffb0366f9691e45c46 Mon Sep 17 00:00:00 2001 From: Gareth Ellis Date: Tue, 1 Dec 2015 13:07:56 +0000 Subject: [PATCH] Add helper method to shell class for loading/fetching helper instances --- lib/Cake/Console/Shell.php | 30 ++++++++++++++++++++++++ lib/Cake/Test/Case/Console/ShellTest.php | 22 +++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/lib/Cake/Console/Shell.php b/lib/Cake/Console/Shell.php index 830181949..aff88e7bb 100644 --- a/lib/Cake/Console/Shell.php +++ b/lib/Cake/Console/Shell.php @@ -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 * diff --git a/lib/Cake/Test/Case/Console/ShellTest.php b/lib/Cake/Test/Case/Console/ShellTest.php index c7f5d86f7..53ca60b88 100644 --- a/lib/Cake/Test/Case/Console/ShellTest.php +++ b/lib/Cake/Test/Case/Console/ShellTest.php @@ -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"); + } + }