Last active
March 1, 2019 20:19
-
-
Save jakzal/4ba5ad5a8cd786c2f37a to your computer and use it in GitHub Desktop.
Starting a PHP built in server in phpunit tests
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 | |
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(); | |
} | |
/** | |
* @after | |
*/ | |
public function clearBackgroundProcessOutput() | |
{ | |
self::$process->clearOutput(); | |
self::$process->clearErrorOutput(); | |
} | |
/** | |
* Returns a command to run in background. | |
* | |
* @return string | |
*/ | |
abstract protected static function getCommand(); | |
} |
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 | |
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