Skip to content

Instantly share code, notes, and snippets.

@abbadon1334
Forked from jakzal/BackgroundProcess.php
Last active March 2, 2019 07:04
Show Gist options
  • Save abbadon1334/51194fe5fb37c7172eeee17e6171f24e to your computer and use it in GitHub Desktop.
Save abbadon1334/51194fe5fb37c7172eeee17e6171f24e to your computer and use it in GitHub Desktop.
Starting a PHP built in server in phpunit tests
<?php
namespace Zalas\Test;
use Symfony\Component\Process\Process;
trait BackgroundProcess
{
/**
* @var Process
*/
private static $process;
/**
* @beforeClass
*/
public static function startBackgroundProcess()
{
self::$process = new Process(self::getCommand());
self::$process->start();
}
/**
* @beforeClass
*/
public static function verifyBackgroundProcessStarted()
{
if (!self::$process->isRunning()) {
throw new \RuntimeException(sprintf(
'Failed to start "%s" in background: %s',
self::$process->getCommandLine(),
self::$process->getErrorOutput()
));
}
}
/**
* @afterClass
*/
public static function stopBackgroundProcess()
{
self::$process->stop(0,9); // 9 to die for sure
}
/**
* @after
*/
public function clearBackgroundProcessOutput()
{
self::$process->clearOutput();
self::$process->clearErrorOutput();
}
/**
* Returns a command to run in background.
*
* @return string
*/
abstract protected static function getCommand();
}
<?php
namespace Zalas\Test;
trait PhpServerProcess
{
use BackgroundProcess;
protected static function getCommand()
{
return self::getPhpServerCommand();
}
protected static function getPhpServerCommand()
{
$rootDir = self::getPhpServerOption('root_dir');
$router = self::getPhpServerOption('router');
$host = self::getPhpServerOption('host', 'localhost');
$port = self::getPhpServerOption('port', 8000);
return sprintf(
'php -S %s:%d%s%s',
$host,
$port,
$rootDir ? ' -t '.$rootDir : '',
$router ? ' '.$router : ''
);
}
protected static function getPhpServerOptions()
{
return [
'host' => 'localhost',
'port' => 8000,
'root_dir' => null,
'router' => null
];
}
private static function getPhpServerOption($option, $default = null)
{
$options = self::getPhpServerOptions();
return array_key_exists($option, $options) ? $options[$option] : $default;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment