<?php

class Process {

	private $_command = null;
	private $_args = [];
	private $_env = [];
	private $_cwd = null;

	private $_pipes = [];

	private $_stdout = [];
	private $_stderr = [];

	private $_fd = null;
	private $_status = null;

	public function __construct($command) {
		$this->_command = $command;
		$this->_env = $_ENV;
	}

	public function arg($v) {
		$this->_args[] = $v;
	}

	public function env($k, $v) {
		$this->_env[$k] = $v;
	}

	public function cwd($p) {
		$this->_cwd = $p;
	}

	public function execute() {
		$command = [];
		$command[] = escapeshellcmd($this->_command);
		foreach ($this->_args as $a) {
			$command[] = escapeshellarg($a);
		}

		$desc = [
			["pipe", "r"],
			["pipe", "w"],
			["pipe", "w"]
		];

		$this->_fd = proc_open(
			implode(" ", $command),
			$desc,
			$this->_pipes,
			$this->_cwd,
			$this->_env
		);

		fclose($this->_pipes[0]); // stdin

		$this->_status = proc_get_status($this->_fd);
		while ($this->_status["running"]) {

			$this->_stdout[] = stream_get_contents($this->_pipes[1]);
			$this->_stderr[] = stream_get_contents($this->_pipes[2]);

			$this->_status = proc_get_status($this->_fd);
		}
			
		proc_close($this->_fd);

		return $this->_status["exitcode"];
	}


	public function stdout() {
		return explode("\n", implode("", $this->_stdout));
	}

	public function stderr() {
		return explode("\n", implode("", $this->_stderr));
	}


}
