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