-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPerfbaseClientProvider.php
More file actions
80 lines (63 loc) · 2.13 KB
/
PerfbaseClientProvider.php
File metadata and controls
80 lines (63 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php
declare(strict_types=1);
namespace Perfbase\Symfony\Support;
use Perfbase\SDK\Config;
use Perfbase\SDK\Perfbase;
class PerfbaseClientProvider
{
/** @var array<string, mixed> */
private array $config;
private PerfbaseErrorHandler $errorHandler;
/** @var callable */
private $clientFactory;
private ?Perfbase $client = null;
private bool $initialized = false;
/**
* @param array<string, mixed> $config
* @param callable|null $clientFactory
*/
public function __construct(array $config, PerfbaseErrorHandler $errorHandler, $clientFactory = null)
{
$this->config = $config;
$this->errorHandler = $errorHandler;
$this->clientFactory = $clientFactory ?? static function (Config $config): Perfbase {
return new Perfbase($config);
};
}
public function getClient(): ?Perfbase
{
if ($this->initialized) {
return $this->client;
}
$this->initialized = true;
try {
$sdkConfig = Config::fromArray([
'api_key' => (string) ($this->config['api_key'] ?? ''),
'api_url' => (string) ($this->config['api_url'] ?? 'https://ingress.perfbase.cloud'),
'flags' => (int) ($this->config['flags'] ?? 0),
'timeout' => (int) ($this->config['timeout'] ?? 10),
'proxy' => $this->normalizeProxy($this->config['proxy'] ?? null),
]);
$factory = $this->clientFactory;
$client = $factory($sdkConfig);
if (!$client instanceof Perfbase) {
throw new \RuntimeException('Perfbase client factory must return a Perfbase instance.');
}
$this->client = $client;
} catch (\Throwable $throwable) {
$this->client = null;
$this->errorHandler->handle($throwable, 'sdk_init');
}
return $this->client;
}
/**
* @param mixed $proxy
*/
private function normalizeProxy($proxy): ?string
{
if (!is_string($proxy) || $proxy === '') {
return null;
}
return $proxy;
}
}