Skip to content

Commit

Permalink
Add the hability to run the built-in server using specific user
Browse files Browse the repository at this point in the history
Signed-off-by: Vitor Mattos <vitor@php.rio>
  • Loading branch information
vitormattos committed May 28, 2023
1 parent 633af89 commit 9716255
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
9 changes: 8 additions & 1 deletion src/RunServerListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ class RunServerListener implements EventSubscriberInterface
private static int $port = 0;
private ?int $verbose = null;
private string $rootDir;
private string $runAs = '';
private static self $instance;

public function __construct(?int $verbose, string $rootDir, string $host)
Expand Down Expand Up @@ -79,6 +80,10 @@ public function start(): void

$cmd = 'php -S ' . self::$host .':' . self::$port . ' -t ' . $script;

if ($this->runAs) {
$cmd = 'runuser -u ' . $this->runAs . ' -- ' . $cmd;
}

if (is_numeric($this->verbose)) {
$verbose = '';
} else {
Expand Down Expand Up @@ -195,8 +200,10 @@ public function getPort()
* Let the OS find an open port for you.
*
* @return int
*
* @psalm-return int<1, max>
*/
private function findOpenPort()
private function findOpenPort(): int
{
$sock = socket_create(AF_INET, SOCK_STREAM, 0);

Expand Down
16 changes: 15 additions & 1 deletion src/Server.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@ public function configure(ArrayNodeDefinition $builder): void
->info('Host domain or IP')
->defaultValue('localhost')
->end()
->scalarNode('runAs')
->info('The username to be used to run the built-in server')
->defaultValue('')
->end()
->end()
;
}
Expand All @@ -88,9 +92,10 @@ public function load(ContainerBuilder $container, array $config): void
}
}
$host = $this->getHost($config);
$runAs = $this->getRunAs($config);
$definition = (new Definition('PhpBuiltin\RunServerListener'))
->addTag('event_dispatcher.subscriber')
->setArguments([$verbose, $rootDir, $host])
->setArguments([$verbose, $rootDir, $host, $runAs])
;

$container->setDefinition(self::ID . '.listener', $definition);
Expand All @@ -105,6 +110,15 @@ private function getHost(array $config): string
return (string) $host;
}

private function getRunAs(array $config): string
{
$runAs = getenv('BEHAT_RUN_AS');
if ($runAs === false) {
$runAs = $config['runAs'];
}
return (string) $runAs;
}

private function getRootDir(array $config): string
{
$rootDir = getenv('BEHAT_ROOT_DIR');
Expand Down

0 comments on commit 9716255

Please sign in to comment.