Last active
October 1, 2021 21:16
-
-
Save marcobrt/72b2a3d1b0649c1bf738c9fc88f74ec0 to your computer and use it in GitHub Desktop.
Singleton PHP class used to keep an instance of gnparser open in streaming mode.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* MIT License | |
* | |
* Copyright (c) 2021 Marco Bortolin | |
*/ | |
class ScientificNameParser | |
{ | |
protected static $parser = null; | |
protected $proc = null; | |
protected $pipes = null; | |
final protected function __construct() {} | |
function __destruct() | |
{ | |
if(is_resource($this->proc)) { | |
fclose($this->pipes[0]); | |
fclose($this->pipes[1]); | |
if(is_resource($this->pipes[2])) { | |
fclose($this->pipes[2]); | |
} | |
proc_close($this->proc); | |
$this->proc = null; | |
} | |
} | |
static public function instance() | |
{ | |
if(self::$parser === null) { | |
self::$parser = new self(); | |
self::$parser->proc = @proc_open(GNPARSER." -s -f compact -d", [ | |
0 => ["pipe", 'r'], | |
1 => ["pipe", 'w'], | |
2 => ['file', TMPDIR.'/gnparser-stderr.log', 'a'], | |
], self::$parser->pipes); | |
if(!is_resource(self::$parser->proc)) { | |
throw new Exception("Cannot create the child process"); | |
} | |
stream_set_blocking(self::$parser->pipes[0], false); | |
stream_set_blocking(self::$parser->pipes[1], false); | |
} | |
return self::$parser; | |
} | |
function parse($scientific_name) | |
{ | |
if(fwrite($this->pipes[0], $scientific_name . "\n" ) == 0) { | |
throw new Exception("Cannot write to stdin"); | |
} | |
stream_select($rx=array($this->pipes[1]), $tx=null, $ex=null, null, null); | |
$stdout = stream_get_contents($this->pipes[1]); | |
if($stdout === false) { | |
throw new Exception("Cannot read from stdout"); | |
} | |
return json_decode($stdout, true); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You need to define:
GNPARSER
with the path to the gnparser executable.TMPDIR
with the path to a directory where to put the stderr file.Usage example: