Code reuse on determining docker container address

This commit is contained in:
Nikola Petkanski
2024-07-16 03:34:41 +03:00
parent 0edcaeec72
commit de59891641
4 changed files with 67 additions and 53 deletions
+4 -25
View File
@@ -6,14 +6,13 @@ namespace Testcontainer\Wait;
use JsonException;
use RuntimeException;
use Symfony\Component\Process\Process;
use Testcontainer\Exception\ContainerNotReadyException;
use Testcontainer\Trait\DockerContainerAwareTrait;
/**
* @phpstan-import-type ContainerInspect from \Testcontainer\Container\Container
*/
final class WaitForTcpPortOpen implements WaitInterface
{
use DockerContainerAwareTrait;
public function __construct(private readonly int $port)
{
}
@@ -28,28 +27,8 @@ final class WaitForTcpPortOpen implements WaitInterface
*/
public function wait(string $id): void
{
if (@fsockopen($this->findContainerAddress($id), $this->port) === false) {
if (@fsockopen($this->getContainerAddress($id), $this->port) === false) {
throw new ContainerNotReadyException($id, new RuntimeException('Unable to connect to container TCP port'));
}
}
/**
* @throws JsonException
*/
private function findContainerAddress(string $id): string
{
$process = new Process(['docker', 'inspect', $id]);
$process->mustRun();
/** @var ContainerInspect $data */
$data = json_decode($process->getOutput(), true, 512, JSON_THROW_ON_ERROR);
$containerAddress = $data[0]['NetworkSettings']['IPAddress'] ?? null;
if (! is_string($containerAddress)) {
throw new ContainerNotReadyException($id, new RuntimeException('Unable to find container IP address'));
}
return $containerAddress;
}
}