PocketMine-MP 5.21.2 git-a6534ecbbbcf369264567d27e5ed70f7f5be9816
Loading...
Searching...
No Matches
ConsoleReader.php
1<?php
2
3/*
4 *
5 * ____ _ _ __ __ _ __ __ ____
6 * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8 * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9 * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * @author PocketMine Team
17 * @link http://www.pocketmine.net/
18 *
19 *
20 */
21
22declare(strict_types=1);
23
24namespace pocketmine\console;
25
27use function fclose;
28use function fgets;
29use function fopen;
30use function is_resource;
31use function stream_select;
32use function trim;
33use function usleep;
34
35final class ConsoleReader{
37 private $stdin;
38
39 public function __construct(){
40 $this->initStdin();
41 }
42
43 private function initStdin() : void{
44 if(is_resource($this->stdin)){
45 fclose($this->stdin);
46 }
47
48 $this->stdin = Utils::assumeNotFalse(fopen("php://stdin", "r"), "Opening stdin should never fail");
49 }
50
54 public function readLine() : ?string{
55 if(!is_resource($this->stdin)){
56 $this->initStdin();
57 }
58
59 $r = [$this->stdin];
60 $w = $e = null;
61 if(($count = stream_select($r, $w, $e, 0, 200000)) === 0){ //nothing changed in 200000 microseconds
62 return null;
63 }elseif($count === false){ //stream error
64 return null;
65 }
66
67 if(($raw = fgets($this->stdin)) === false){ //broken pipe or EOF
68 usleep(200000); //prevent CPU waste if it's end of pipe
69 return null; //loop back round
70 }
71
72 $line = trim($raw);
73
74 return $line !== "" ? $line : null;
75 }
76
77 public function __destruct(){
78 fclose($this->stdin);
79 }
80}