Skip to content

Commit

Permalink
#184 - Client builder with two mandatory options (timeout, connect_ti…
Browse files Browse the repository at this point in the history
…meout)
  • Loading branch information
AloisJasa committed Apr 6, 2023
1 parent 6f61f73 commit 7c2f9f1
Showing 1 changed file with 107 additions and 0 deletions.
107 changes: 107 additions & 0 deletions app/Check/Consumers/Client/ClientBuilder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
<?php declare(strict_types = 1);

namespace Pd\Monitoring\Check\Consumers\Client;

class ClientBuilder
{

private ?int $connectTimeout;

private ?int $timeout;

/**
* @see https://docs.guzzlephp.org/en/stable/request-options.html#verify
*/
private bool $verify = TRUE;

private ?\Pd\Monitoring\Check\Consumers\Client\Conf\AllowRedirectsInterface $allowRedirects = NULL;


private function __construct(
?int $connectTimeout,
?int $timeout
)
{
$this->connectTimeout = $connectTimeout;
$this->timeout = $timeout;
}


public function withVerify(bool $verify): self
{
$factory = clone $this;
$factory->verify = $verify;

return $factory;
}


public function withAllowRedirects(\Pd\Monitoring\Check\Consumers\Client\Conf\AllowRedirectsInterface $allowRedirects): self
{
$factory = clone $this;
$factory->allowRedirects = $allowRedirects;

return $factory;
}


public function withTimeout(int $timeout): self
{
$factory = clone $this;
$factory->timeout = $timeout;

return $factory;
}


public function withConnectTimeout(int $defaultTimeout): self
{
$builder = clone $this;
$builder->connectTimeout = $defaultTimeout;

return $builder;
}


public static function create(
int $connectTimeout,
int $timeout
): self
{
return new self($connectTimeout, $timeout);
}


/**
* @return array<string, string|array<string, string>>
*/
private function config(): array
{
$config = [
'verify' => $this->verify,
'connect_timeout' => $this->connectTimeout,
'timeout' => $this->timeout,
];

$headers = [
'headers' => [
'User-Agent' => 'PeckaMonitoringBot/1.0',
],
];

return \array_filter(
\array_merge(
$config,
$headers,
$this->allowRedirects !== NULL ? $this->allowRedirects->toArray() : []
)
);
}


public function build(): \GuzzleHttp\Client
{
return new \GuzzleHttp\Client($this->config());
}

}

0 comments on commit 7c2f9f1

Please sign in to comment.