CommandReader: Use statics for thread-local storage instead of globals

This commit is contained in:
Dylan K. Taylor 2018-06-06 10:06:52 +01:00
parent 38f4afb17c
commit edd150971e

View File

@ -32,6 +32,9 @@ class CommandReader extends Thread{
public const TYPE_STREAM = 1; public const TYPE_STREAM = 1;
public const TYPE_PIPED = 2; public const TYPE_PIPED = 2;
/** @var resource */
private static $stdin;
/** @var \Threaded */ /** @var \Threaded */
protected $buffer; protected $buffer;
private $shutdown = false; private $shutdown = false;
@ -75,14 +78,12 @@ class CommandReader extends Thread{
} }
private function initStdin(){ private function initStdin(){
global $stdin; if(is_resource(self::$stdin)){
fclose(self::$stdin);
if(is_resource($stdin)){
fclose($stdin);
} }
$stdin = fopen("php://stdin", "r"); self::$stdin = fopen("php://stdin", "r");
if($this->isPipe($stdin)){ if($this->isPipe(self::$stdin)){
$this->type = self::TYPE_PIPED; $this->type = self::TYPE_PIPED;
}else{ }else{
$this->type = self::TYPE_STREAM; $this->type = self::TYPE_STREAM;
@ -113,9 +114,7 @@ class CommandReader extends Thread{
return true; return true;
} }
}else{ }else{
global $stdin; if(!is_resource(self::$stdin)){
if(!is_resource($stdin)){
$this->initStdin(); $this->initStdin();
} }
@ -123,7 +122,7 @@ class CommandReader extends Thread{
/** @noinspection PhpMissingBreakStatementInspection */ /** @noinspection PhpMissingBreakStatementInspection */
case self::TYPE_STREAM: case self::TYPE_STREAM:
//stream_select doesn't work on piped streams for some reason //stream_select doesn't work on piped streams for some reason
$r = [$stdin]; $r = [self::$stdin];
if(($count = stream_select($r, $w, $e, 0, 200000)) === 0){ //nothing changed in 200000 microseconds if(($count = stream_select($r, $w, $e, 0, 200000)) === 0){ //nothing changed in 200000 microseconds
return true; return true;
}elseif($count === false){ //stream error }elseif($count === false){ //stream error
@ -131,7 +130,7 @@ class CommandReader extends Thread{
} }
case self::TYPE_PIPED: case self::TYPE_PIPED:
if(($raw = fgets($stdin)) === false){ //broken pipe or EOF if(($raw = fgets(self::$stdin)) === false){ //broken pipe or EOF
$this->initStdin(); $this->initStdin();
$this->synchronized(function(){ $this->synchronized(function(){
$this->wait(200000); $this->wait(200000);
@ -177,8 +176,7 @@ class CommandReader extends Thread{
while(!$this->shutdown and $this->readLine()); while(!$this->shutdown and $this->readLine());
if($this->type !== self::TYPE_READLINE){ if($this->type !== self::TYPE_READLINE){
global $stdin; fclose(self::$stdin);
fclose($stdin);
} }
} }