ConsoleInput.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. /**
  3. * ConsoleInput file.
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * For full copyright and license information, please see the LICENSE.txt
  12. * Redistributions of files must retain the above copyright notice.
  13. *
  14. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  15. * @link http://cakephp.org CakePHP(tm) Project
  16. * @package Cake.Console
  17. * @since CakePHP(tm) v 2.0
  18. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  19. */
  20. /**
  21. * Object wrapper for interacting with stdin
  22. *
  23. * @package Cake.Console
  24. */
  25. class ConsoleInput {
  26. /**
  27. * Input value.
  28. *
  29. * @var resource
  30. */
  31. protected $_input;
  32. /**
  33. * Can this instance use readline?
  34. * Two conditions must be met:
  35. * 1. Readline support must be enabled.
  36. * 2. Handle we are attached to must be stdin.
  37. * Allows rich editing with arrow keys and history when inputting a string.
  38. *
  39. * @var boolean
  40. */
  41. protected $_canReadline;
  42. /**
  43. * Constructor
  44. *
  45. * @param string $handle The location of the stream to use as input.
  46. */
  47. public function __construct($handle = 'php://stdin') {
  48. $this->_canReadline = extension_loaded('readline') && $handle == 'php://stdin' ? true : false;
  49. $this->_input = fopen($handle, 'r');
  50. }
  51. /**
  52. * Read a value from the stream
  53. *
  54. * @return mixed The value of the stream
  55. */
  56. public function read() {
  57. if ($this->_canReadline) {
  58. $line = readline('');
  59. if (!empty($line)) {
  60. readline_add_history($line);
  61. }
  62. return $line;
  63. }
  64. return fgets($this->_input);
  65. }
  66. /**
  67. * Checks if data is available on the stream
  68. *
  69. * @param integer $timeout An optional time to wait for data
  70. * @return boolean True for data available, false otherwise
  71. */
  72. public function dataAvailable($timeout = 0) {
  73. $readFds = array($this->_input);
  74. $readyFds = stream_select($readFds, $writeFds, $errorFds, $timeout);
  75. return ($readyFds > 0);
  76. }
  77. }