Command.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. <?php
  2. /**
  3. * Lithium: the most rad php framework
  4. *
  5. * @copyright Copyright 2013, Union of RAD (http://union-of-rad.org)
  6. * @license http://opensource.org/licenses/bsd-license.php The BSD License
  7. */
  8. namespace lithium\console;
  9. use Exception;
  10. use lithium\console\command\Help;
  11. /**
  12. * All Commands to be run from the Lithium console must extend this class.
  13. *
  14. * The `run` method is automatically called if it exists. Otherwise, if a method does not exist
  15. * the `Help` command will be run.
  16. *
  17. * {{{
  18. * $ li3 example
  19. * $ li3 example --format=json
  20. * }}}
  21. *
  22. */
  23. class Command extends \lithium\core\Object {
  24. /**
  25. * If -h or --help param exists a help screen will be returned.
  26. * Similar to running `li3 help COMMAND`.
  27. *
  28. * @var boolean
  29. */
  30. public $help = false;
  31. /**
  32. * A Request object.
  33. *
  34. * @see lithium\console\Request
  35. * @var object
  36. */
  37. public $request;
  38. /**
  39. * A Response object.
  40. *
  41. * @see lithium\console\Response
  42. * @var object
  43. */
  44. public $response;
  45. /**
  46. * Only shows only text output without styles.
  47. *
  48. * @var boolean
  49. */
  50. public $plain = false;
  51. /**
  52. * Only shows error output.
  53. *
  54. * @var boolean
  55. */
  56. public $silent = false;
  57. /**
  58. * Dynamic dependencies.
  59. *
  60. * @var array
  61. */
  62. protected $_classes = array(
  63. 'response' => 'lithium\console\Response'
  64. );
  65. /**
  66. * Auto configuration.
  67. *
  68. * @var array
  69. */
  70. protected $_autoConfig = array('classes' => 'merge');
  71. /**
  72. * Constructor.
  73. *
  74. * @param array $config
  75. * @return void
  76. */
  77. public function __construct(array $config = array()) {
  78. $defaults = array('request' => null, 'response' => array(), 'classes' => $this->_classes);
  79. parent::__construct($config + $defaults);
  80. }
  81. /**
  82. * Command Initializer.
  83. *
  84. * Populates the `$response` property with a new instance of the `Response` class passing it
  85. * configuration and assigns the values from named parameters of the request (if applicable) to
  86. * properties of the command.
  87. *
  88. * @return void
  89. */
  90. protected function _init() {
  91. parent::_init();
  92. $this->request = $this->_config['request'];
  93. if (!is_object($this->request) || !$this->request->params) {
  94. return;
  95. }
  96. $this->response = $this->_config['response'];
  97. if (!is_object($this->response)) {
  98. $this->response = $this->_instance('response', $this->response);
  99. }
  100. $default = array('command' => null, 'action' => null, 'args' => null);
  101. $params = array_diff_key((array) $this->request->params, $default);
  102. foreach ($params as $key => $param) {
  103. $this->{$key} = $param;
  104. }
  105. }
  106. /**
  107. * Called by the `Dispatcher` class to invoke an action.
  108. *
  109. * @see lithium\console\Dispatcher
  110. * @see lithium\console\Response
  111. * @param string $action The name of the method to run.
  112. * @param array $args The arguments from the request.
  113. * @param array $options
  114. * @return object The response object associated with this command.
  115. * @todo Implement filters.
  116. */
  117. public function __invoke($action, $args = array(), $options = array()) {
  118. try {
  119. $this->response->status = 1;
  120. $result = $this->invokeMethod($action, $args);
  121. if (is_int($result)) {
  122. $this->response->status = $result;
  123. } elseif ($result || $result === null) {
  124. $this->response->status = 0;
  125. }
  126. } catch (Exception $e) {
  127. $this->error($e->getMessage());
  128. }
  129. return $this->response;
  130. }
  131. /**
  132. * Invokes the `Help` command.
  133. *
  134. * The invoked Help command will take over request and response objects of
  135. * the originally invoked command. Thus the response of the Help command
  136. * becomes the response of the original one.
  137. *
  138. * @return boolean
  139. */
  140. protected function _help() {
  141. $help = new Help(array(
  142. 'request' => $this->request,
  143. 'response' => $this->response,
  144. 'classes' => $this->_classes
  145. ));
  146. return $help->run(get_class($this));
  147. }
  148. /**
  149. * Writes a string to the output stream.
  150. *
  151. * @param string $output The string to write.
  152. * @param integer|string|array $options
  153. * integer as the number of new lines.
  154. * string as the style
  155. * array as :
  156. * - nl : number of new lines to add at the end
  157. * - style : the style name to wrap around the
  158. * @return integer
  159. */
  160. public function out($output = null, $options = array('nl' => 1)) {
  161. if ($this->silent) {
  162. return;
  163. }
  164. return $this->_response('output', $output, $options);
  165. }
  166. /**
  167. * Writes a string to error stream.
  168. *
  169. * @param string $error The string to write.
  170. * @param integer|string|array $options
  171. * integer as the number of new lines.
  172. * string as the style
  173. * array as :
  174. * - nl : number of new lines to add at the end
  175. * - style : the style name to wrap around the
  176. * @return integer
  177. */
  178. public function error($error = null, $options = array('nl' => 1)) {
  179. return $this->_response('error', $error, $options);
  180. }
  181. /**
  182. * Handles input. Will continue to loop until `$options['quit']` or
  183. * result is part of `$options['choices']`.
  184. *
  185. * @param string $prompt
  186. * @param array $options
  187. * @return string Returns the result of the input data. If the input is equal to the `quit`
  188. * option boolean `false` is returned
  189. */
  190. public function in($prompt = null, array $options = array()) {
  191. $defaults = array('choices' => null, 'default' => null, 'quit' => 'q');
  192. $options += $defaults;
  193. $choices = null;
  194. if (is_array($options['choices'])) {
  195. $choices = '(' . implode('/', $options['choices']) . ')';
  196. }
  197. $default = $options['default'] ? "[{$options['default']}] " : '';
  198. do {
  199. $this->out("{$prompt} {$choices} \n {$default}> ", false);
  200. $result = trim($this->request->input());
  201. } while (
  202. !empty($options['choices']) && !in_array($result, $options['choices'], true)
  203. && (empty($options['quit']) || $result !== $options['quit'])
  204. && (!$options['default'] || $result !== '')
  205. );
  206. if ($result == $options['quit']) {
  207. return false;
  208. }
  209. if ($options['default'] !== null && $result == '') {
  210. return $options['default'];
  211. }
  212. return $result;
  213. }
  214. /**
  215. * Writes a header to the output stream. In addition to the actual text,
  216. * horizontal lines before and afterwards are written. The lines will have
  217. * the same length as the text. This behavior can be modified by providing
  218. * the length of lines as a second paramerter.
  219. *
  220. * Given the text `'Lithium'` this generates following output:
  221. *
  222. * {{{
  223. * -------
  224. * Lithium
  225. * -------
  226. * }}}
  227. *
  228. * @param string $text The heading text.
  229. * @param integer $line The length of the line. Defaults to the length of text.
  230. * @return void
  231. */
  232. public function header($text, $line = null) {
  233. if (!$line) {
  234. $line = strlen($text);
  235. }
  236. $this->hr($line);
  237. $this->out($text, 1, 'heading');
  238. $this->hr($line);
  239. }
  240. /**
  241. * Writes rows of columns.
  242. *
  243. * This method expects asceding integer values as the keys, which map to the appropriate
  244. * columns. Currently, there is no special "header" option, but you can define them for your
  245. * own.
  246. *
  247. * Example Usage:
  248. *
  249. * {{{
  250. * $output = array(
  251. * array('Name', 'Age'),
  252. * array('----', '---'),
  253. * );
  254. * foreach($users as $user) {
  255. * $output[] = array($user->name, $user->age);
  256. * }
  257. * $this->columns($output);
  258. * }}}
  259. *
  260. * Would render something similar to:
  261. *
  262. * {{{
  263. * Name Age
  264. * ---- ---
  265. * Jane Doe 22
  266. * Foo Bar 18
  267. * }}}
  268. *
  269. * This method also calculates the needed space between the columns. All option params given
  270. * also get passed down to the `out()` method, which allow custom formatting. Passing something
  271. * like `$this->columns($output, array('style' => 'red)` would print the table in red.
  272. *
  273. * @see lithium\console\Response::styles()
  274. * @param array $rows The rows to print, with each column as an array element.
  275. * @param array $options Optional params:
  276. * - separator : Different column separator, defaults to `\t`
  277. * - style : the style name to wrap around the columns output
  278. * @return void
  279. */
  280. public function columns($rows, $options = array()) {
  281. $defaults = array('separator' => "\t", "error" => false);
  282. $options += $defaults;
  283. $lengths = array_reduce($rows, function($columns, $row) {
  284. foreach ((array) $row as $key => $val) {
  285. if (!isset($columns[$key]) || strlen($val) > $columns[$key]) {
  286. $columns[$key] = strlen($val);
  287. }
  288. }
  289. return $columns;
  290. });
  291. $rows = array_reduce($rows, function($rows, $row) use ($lengths, $options) {
  292. $text = '';
  293. foreach ((array) $row as $key => $val) {
  294. $text = $text . str_pad($val, $lengths[$key]) . $options['separator'];
  295. }
  296. $rows[] = $text;
  297. return $rows;
  298. });
  299. if ($options['error']) {
  300. $this->error($rows, $options);
  301. return;
  302. }
  303. $this->out($rows, $options);
  304. }
  305. /**
  306. * Add newlines ("\n") a given number of times and return them in a single string.
  307. *
  308. * @param integer $number The number of new lines to fill into a string.
  309. * @return string
  310. */
  311. public function nl($number = 1) {
  312. return str_repeat("\n", $number);
  313. }
  314. /**
  315. * Adds a horizontal line to output stream.
  316. *
  317. * @param integer $length The length of the line, defaults to 80.
  318. * @param integer $newlines How many new lines to print afterwards, defaults to 1.
  319. * @return integer
  320. */
  321. public function hr($length = 80, $newlines = 1) {
  322. return $this->out(str_repeat('-', $length), $newlines);
  323. }
  324. /**
  325. * Clears the entire screen.
  326. *
  327. * @return void
  328. */
  329. public function clear() {
  330. passthru(strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' ? 'cls' : 'clear');
  331. }
  332. /**
  333. * Stop execution, by exiting the script.
  334. *
  335. * @param integer $status Numeric value that will be used on `exit()`.
  336. * @param boolean $message An optional message that will be written to the stream.
  337. * @return void
  338. */
  339. public function stop($status = 0, $message = null) {
  340. if ($message) {
  341. ($status == 0) ? $this->out($message) : $this->error($message);
  342. }
  343. exit($status);
  344. }
  345. /**
  346. * Handles the response that is sent to the stream.
  347. *
  348. * @param string $type the stream either output or error
  349. * @param string $string the message to render
  350. * @param integer|string|array $options
  351. * integer as the number of new lines.
  352. * string as the style
  353. * array as :
  354. * - nl : number of new lines to add at the end
  355. * - style : the style name to wrap around the
  356. * @return void
  357. */
  358. protected function _response($type, $string, $options) {
  359. $defaults = array('nl' => 1, 'style' => null);
  360. if (!is_array($options)) {
  361. if (!$options || is_int($options)) {
  362. $options = array('nl' => $options);
  363. } else if (is_string($options)) {
  364. $options = array('style' => $options);
  365. } else {
  366. $options = array();
  367. }
  368. }
  369. $options += $defaults;
  370. if (is_array($string)) {
  371. $method = ($type == 'error' ? $type : 'out');
  372. foreach ($string as $out) {
  373. $this->{$method}($out, $options);
  374. }
  375. return;
  376. }
  377. extract($options);
  378. if ($style !== null && !$this->plain) {
  379. $string = "{:{$style}}{$string}{:end}";
  380. }
  381. if ($nl) {
  382. $string = $string . $this->nl($nl);
  383. }
  384. return $this->response->{$type}($string);
  385. }
  386. }
  387. ?>