Prompt.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. <?php
  2. namespace Laravel\Prompts;
  3. use Closure;
  4. use Laravel\Prompts\Exceptions\FormRevertedException;
  5. use Laravel\Prompts\Output\ConsoleOutput;
  6. use Laravel\Prompts\Support\Result;
  7. use RuntimeException;
  8. use Symfony\Component\Console\Output\OutputInterface;
  9. use Throwable;
  10. abstract class Prompt
  11. {
  12. use Concerns\Colors;
  13. use Concerns\Cursor;
  14. use Concerns\Erase;
  15. use Concerns\Events;
  16. use Concerns\FakesInputOutput;
  17. use Concerns\Fallback;
  18. use Concerns\Interactivity;
  19. use Concerns\Themes;
  20. /**
  21. * The current state of the prompt.
  22. */
  23. public string $state = 'initial';
  24. /**
  25. * The error message from the validator.
  26. */
  27. public string $error = '';
  28. /**
  29. * The cancel message displayed when this prompt is cancelled.
  30. */
  31. public string $cancelMessage = 'Cancelled.';
  32. /**
  33. * The previously rendered frame.
  34. */
  35. protected string $prevFrame = '';
  36. /**
  37. * How many new lines were written by the last output.
  38. */
  39. protected int $newLinesWritten = 1;
  40. /**
  41. * Whether user input is required.
  42. */
  43. public bool|string $required;
  44. /**
  45. * The transformation callback.
  46. */
  47. public ?Closure $transform = null;
  48. /**
  49. * The validator callback or rules.
  50. */
  51. public mixed $validate;
  52. /**
  53. * The cancellation callback.
  54. */
  55. protected static ?Closure $cancelUsing;
  56. /**
  57. * Indicates if the prompt has been validated.
  58. */
  59. protected bool $validated = false;
  60. /**
  61. * The custom validation callback.
  62. */
  63. protected static ?Closure $validateUsing;
  64. /**
  65. * The revert handler from the StepBuilder.
  66. */
  67. protected static ?Closure $revertUsing = null;
  68. /**
  69. * The output instance.
  70. */
  71. protected static OutputInterface $output;
  72. /**
  73. * The terminal instance.
  74. */
  75. protected static Terminal $terminal;
  76. /**
  77. * Get the value of the prompt.
  78. */
  79. abstract public function value(): mixed;
  80. /**
  81. * Render the prompt and listen for input.
  82. */
  83. public function prompt(): mixed
  84. {
  85. try {
  86. $this->capturePreviousNewLines();
  87. if (static::shouldFallback()) {
  88. return $this->fallback();
  89. }
  90. static::$interactive ??= stream_isatty(STDIN);
  91. if (! static::$interactive) {
  92. return $this->default();
  93. }
  94. $this->checkEnvironment();
  95. try {
  96. static::terminal()->setTty('-icanon -isig -echo');
  97. } catch (Throwable $e) {
  98. static::output()->writeln("<comment>{$e->getMessage()}</comment>");
  99. static::fallbackWhen(true);
  100. return $this->fallback();
  101. }
  102. $this->hideCursor();
  103. $this->render();
  104. $result = $this->runLoop(function (string $key): ?Result {
  105. $continue = $this->handleKeyPress($key);
  106. $this->render();
  107. if ($continue === false || $key === Key::CTRL_C) {
  108. if ($key === Key::CTRL_C) {
  109. if (isset(static::$cancelUsing)) {
  110. return Result::from((static::$cancelUsing)());
  111. } else {
  112. static::terminal()->exit();
  113. }
  114. }
  115. if ($key === Key::CTRL_U && self::$revertUsing) {
  116. throw new FormRevertedException;
  117. }
  118. return Result::from($this->transformedValue());
  119. }
  120. // Continue looping.
  121. return null;
  122. });
  123. return $result;
  124. } finally {
  125. $this->clearListeners();
  126. }
  127. }
  128. /**
  129. * Implementation of the prompt looping mechanism.
  130. *
  131. * @param callable(string $key): ?Result $callable
  132. */
  133. public function runLoop(callable $callable): mixed
  134. {
  135. while (($key = static::terminal()->read()) !== null) {
  136. /**
  137. * If $key is an empty string, Terminal::read
  138. * has failed. We can continue to the next
  139. * iteration of the loop, and try again.
  140. */
  141. if ($key === '') {
  142. continue;
  143. }
  144. $result = $callable($key);
  145. if ($result instanceof Result) {
  146. return $result->value;
  147. }
  148. }
  149. }
  150. /**
  151. * Register a callback to be invoked when a user cancels a prompt.
  152. */
  153. public static function cancelUsing(?Closure $callback): void
  154. {
  155. static::$cancelUsing = $callback;
  156. }
  157. /**
  158. * How many new lines were written by the last output.
  159. */
  160. public function newLinesWritten(): int
  161. {
  162. return $this->newLinesWritten;
  163. }
  164. /**
  165. * Capture the number of new lines written by the last output.
  166. */
  167. protected function capturePreviousNewLines(): void
  168. {
  169. $this->newLinesWritten = method_exists(static::output(), 'newLinesWritten')
  170. ? static::output()->newLinesWritten()
  171. : 1;
  172. }
  173. /**
  174. * Set the output instance.
  175. */
  176. public static function setOutput(OutputInterface $output): void
  177. {
  178. self::$output = $output;
  179. }
  180. /**
  181. * Get the current output instance.
  182. */
  183. protected static function output(): OutputInterface
  184. {
  185. return self::$output ??= new ConsoleOutput;
  186. }
  187. /**
  188. * Write output directly, bypassing newline capture.
  189. */
  190. protected static function writeDirectly(string $message): void
  191. {
  192. match (true) {
  193. method_exists(static::output(), 'writeDirectly') => static::output()->writeDirectly($message),
  194. method_exists(static::output(), 'getOutput') => static::output()->getOutput()->write($message),
  195. default => static::output()->write($message),
  196. };
  197. }
  198. /**
  199. * Get the terminal instance.
  200. */
  201. public static function terminal(): Terminal
  202. {
  203. return static::$terminal ??= new Terminal;
  204. }
  205. /**
  206. * Set the custom validation callback.
  207. */
  208. public static function validateUsing(Closure $callback): void
  209. {
  210. static::$validateUsing = $callback;
  211. }
  212. /**
  213. * Revert the prompt using the given callback.
  214. *
  215. * @internal
  216. */
  217. public static function revertUsing(Closure $callback): void
  218. {
  219. static::$revertUsing = $callback;
  220. }
  221. /**
  222. * Clear any previous revert callback.
  223. *
  224. * @internal
  225. */
  226. public static function preventReverting(): void
  227. {
  228. static::$revertUsing = null;
  229. }
  230. /**
  231. * Render the prompt.
  232. */
  233. protected function render(): void
  234. {
  235. $this->terminal()->initDimensions();
  236. $frame = $this->renderTheme();
  237. if ($frame === $this->prevFrame) {
  238. return;
  239. }
  240. if ($this->state === 'initial') {
  241. static::output()->write($frame);
  242. $this->state = 'active';
  243. $this->prevFrame = $frame;
  244. return;
  245. }
  246. $terminalHeight = $this->terminal()->lines();
  247. $previousFrameHeight = count(explode(PHP_EOL, $this->prevFrame));
  248. $renderableLines = array_slice(explode(PHP_EOL, $frame), abs(min(0, $terminalHeight - $previousFrameHeight)));
  249. $this->moveCursorToColumn(1);
  250. $this->moveCursorUp(min($terminalHeight, $previousFrameHeight) - 1);
  251. $this->eraseDown();
  252. $this->output()->write(implode(PHP_EOL, $renderableLines));
  253. $this->prevFrame = $frame;
  254. }
  255. /**
  256. * Submit the prompt.
  257. */
  258. protected function submit(): void
  259. {
  260. $this->validate($this->transformedValue());
  261. if ($this->state !== 'error') {
  262. $this->state = 'submit';
  263. }
  264. }
  265. /**
  266. * Handle a key press and determine whether to continue.
  267. */
  268. private function handleKeyPress(string $key): bool
  269. {
  270. if ($this->state === 'error') {
  271. $this->state = 'active';
  272. }
  273. $this->emit('key', $key);
  274. if ($this->state === 'submit') {
  275. return false;
  276. }
  277. if ($key === Key::CTRL_U) {
  278. if (! self::$revertUsing) {
  279. $this->state = 'error';
  280. $this->error = 'This cannot be reverted.';
  281. return true;
  282. }
  283. $this->state = 'cancel';
  284. $this->cancelMessage = 'Reverted.';
  285. call_user_func(self::$revertUsing);
  286. return false;
  287. }
  288. if ($key === Key::CTRL_C) {
  289. $this->state = 'cancel';
  290. return false;
  291. }
  292. if ($this->validated) {
  293. $this->validate($this->transformedValue());
  294. }
  295. return true;
  296. }
  297. /**
  298. * Transform the input.
  299. */
  300. private function transform(mixed $value): mixed
  301. {
  302. if (is_null($this->transform)) {
  303. return $value;
  304. }
  305. return call_user_func($this->transform, $value);
  306. }
  307. /**
  308. * Get the transformed value of the prompt.
  309. */
  310. protected function transformedValue(): mixed
  311. {
  312. return $this->transform($this->value());
  313. }
  314. /**
  315. * Validate the input.
  316. */
  317. private function validate(mixed $value): void
  318. {
  319. $this->validated = true;
  320. if ($this->required !== false && $this->isInvalidWhenRequired($value)) {
  321. $this->state = 'error';
  322. $this->error = is_string($this->required) && strlen($this->required) > 0 ? $this->required : 'Required.';
  323. return;
  324. }
  325. if (! isset($this->validate) && ! isset(static::$validateUsing)) {
  326. return;
  327. }
  328. $error = match (true) {
  329. is_callable($this->validate) => ($this->validate)($value),
  330. isset(static::$validateUsing) => (static::$validateUsing)($this),
  331. default => throw new RuntimeException('The validation logic is missing.'),
  332. };
  333. if (! is_string($error) && ! is_null($error)) {
  334. throw new RuntimeException('The validator must return a string or null.');
  335. }
  336. if (is_string($error) && strlen($error) > 0) {
  337. $this->state = 'error';
  338. $this->error = $error;
  339. }
  340. }
  341. /**
  342. * Determine whether the given value is invalid when the prompt is required.
  343. */
  344. protected function isInvalidWhenRequired(mixed $value): bool
  345. {
  346. return $value === '' || $value === [] || $value === false || $value === null;
  347. }
  348. /**
  349. * Check whether the environment can support the prompt.
  350. */
  351. private function checkEnvironment(): void
  352. {
  353. if (PHP_OS_FAMILY === 'Windows') {
  354. throw new RuntimeException('Prompts is not currently supported on Windows. Please use WSL or configure a fallback.');
  355. }
  356. }
  357. /**
  358. * Restore the cursor and terminal state.
  359. */
  360. public function __destruct()
  361. {
  362. $this->restoreCursor();
  363. static::terminal()->restoreTty();
  364. }
  365. }