1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Blackmine\Client; |
6
|
|
|
|
7
|
|
|
use Error; |
8
|
|
|
|
9
|
|
|
class ClientOptions |
10
|
|
|
{ |
11
|
|
|
public const CLIENT_OPTION_BASE_URL = "base_url"; |
12
|
|
|
public const CLIENT_OPTION_API_KEY = "api_key"; |
13
|
|
|
public const CLIENT_OPTION_FORMAT = "format"; |
14
|
|
|
public const CLIENT_OPTION_REQUEST_HEADERS = "headers"; |
15
|
|
|
public const CLIENT_OPTIONS_ACTING_AS = "acting_as"; |
16
|
|
|
public const CLIENT_OPTIONS_CACHE_TTL = "cache_ttl"; |
17
|
|
|
|
18
|
|
|
public const CACHE_DEFAULT_TTL = 3600; |
19
|
|
|
|
20
|
|
|
public const REDMINE_API_KEY_HEADER = "X-Redmine-API-Key"; |
21
|
|
|
public const REDMINE_IMPERSONATE_HEADER = "X-Redmine-Switch-User"; |
22
|
|
|
|
23
|
|
|
protected static array $mandatory_options = [ |
24
|
|
|
self::CLIENT_OPTION_BASE_URL, |
25
|
|
|
self::CLIENT_OPTION_API_KEY |
26
|
|
|
]; |
27
|
|
|
|
28
|
|
|
protected static array $default_headers = [ |
29
|
|
|
"Content-Type" => "application/json", |
30
|
|
|
"User-Agent" => "Blackmine API Client v1.0", |
31
|
|
|
"Cache-Control" => "no-cache" |
32
|
|
|
]; |
33
|
|
|
|
34
|
|
|
public function __construct(protected array $options) |
35
|
|
|
{ |
36
|
|
|
if ($this->validate()) { |
37
|
|
|
$this->initHeaders(); |
38
|
|
|
$this->initFormat(); |
39
|
|
|
} |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
public function get(string $option): mixed |
43
|
|
|
{ |
44
|
|
|
return $this->options[$option] ?? null; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
protected function validate(): bool |
48
|
|
|
{ |
49
|
|
|
foreach (self::$mandatory_options as $mandatory_option) { |
50
|
|
|
if (!array_key_exists($mandatory_option, $this->options)) { |
51
|
|
|
throw new Error("Mandatory option " . $mandatory_option . " not found in options"); |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
return true; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
protected function initHeaders(): void |
59
|
|
|
{ |
60
|
|
|
$this->options[self::CLIENT_OPTION_REQUEST_HEADERS][self::REDMINE_API_KEY_HEADER] = |
61
|
|
|
$this->options[self::CLIENT_OPTION_API_KEY]; |
62
|
|
|
$this->options[self::CLIENT_OPTION_REQUEST_HEADERS][self::REDMINE_IMPERSONATE_HEADER] = |
63
|
|
|
$this->options[self::CLIENT_OPTIONS_ACTING_AS] ?? null; |
64
|
|
|
$this->options[self::CLIENT_OPTION_REQUEST_HEADERS] = array_merge( |
65
|
|
|
self::$default_headers, |
66
|
|
|
$this->options[self::CLIENT_OPTION_REQUEST_HEADERS] |
67
|
|
|
); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
protected function initFormat(): void |
71
|
|
|
{ |
72
|
|
|
if (!isset($this->options[self::CLIENT_OPTION_FORMAT])) { |
73
|
|
|
$this->options[self::CLIENT_OPTION_FORMAT] = ClientInterface::REDMINE_FORMAT_JSON; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|