<?php

class Process
{
  public string $Command;
  public $Handle;
  public array $Pipes;
  public array $Environment;
  public ?string $WorkingDir;

  function __construct()
  {
    $this->Command = '';
    $this->Handle = null;
    $this->Pipes = array();
    $this->Environment = array();
    $this->WorkingDir = null;
  }

  function Start(): void
  {
    if (!$this->IsRunning())
    {
      $DescriptorSpec = array(
        0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
        1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
        2 => array("pipe", "w")   // stderr is a pipe that the child will write to
      );

      $this->Handle = proc_open($this->Command, $DescriptorSpec, $this->Pipes,
        $this->WorkingDir, $this->Environment);
      stream_set_blocking($this->Pipes[0], FALSE);
      stream_set_blocking($this->Pipes[1], FALSE);
      stream_set_blocking($this->Pipes[2], FALSE);
    }
  }

  function Stop(): void
  {
    if ($this->IsRunning())
    {
      proc_close($this->Handle);
      $this->Handle = null;
    }
  }

  function IsRunning(): bool
  {
    return is_resource($this->Handle);
  }
}
