<?php
namespace Engine\Os\Command;

/**
 * Execute php script in cli. This class should be used only for MVC scripts.
 * @author oana
 */
class AsyncPhpScript extends \Engine\Os\Command\Process
{
	/**
	 * Priority
	 * @var String
	 */
	protected $priority = 19;

	/**
	 * Script arguments
	 */
	protected $arguments = "";

	public function __construct($command=NULL)
	{
		$this->command = escapeshellarg(APP_REAL_PATH.'disp.php');
	}

	/**
	 * Set priority
	 * @return \Engine\Os\Command\AsyncPhpScript
	 */
	public function setPriority($priority)
	{
		$this->priority = $priority;
		return $this;
	}

	/**
	 * Set arguments
	 * @return \Engine\Os\Command\AsyncPhpScript
	 */
	public function setArguments($arguments)
	{
		$this->arguments = $arguments;
		return $this;
	}

	/**
	 * Add an argument using the standard syntax "arg=value"
	 * @param string $option
	 * @param string $value
	 */
	public function addArgument($option, $value=null)
	{
		$this->arguments.= sprintf(" %s=%s", $option, escapeshellarg($value));
		return $this;
	}

	/**
	 * Execute script in cli(non-PHPdoc)
	 * @see \Engine\Os\Command\Process::doRun()
	 */
	protected function doRun($command, $outputFile, $async, $captureErrors) :void
	{
		$php = "php -f";

		$nice = '';
		if ($this->priority) {
			$nice = "nice -n {$this->priority}";
		}

		$command = trim("{$nice} {$php} {$this->command} {$this->arguments}");

		parent::doRun($command, $outputFile, $async, $captureErrors);
	}
}