fix: use-before-init in Ntfy

This commit is contained in:
Gottfried Mayer 2023-11-06 09:33:31 +00:00
parent b88d69069f
commit fdede08444
1 changed files with 19 additions and 26 deletions

View File

@ -8,42 +8,24 @@ class Ntfy
{
private string $topic;
private ?string $token;
private string $serverUrl = 'https://ntfy.sh';
private string $serverUrl;
private const DEFAULT_URL = 'https://ntfy.sh';
public function __construct(?string $topic = null, ?string $token = null, ?string $serverUrl = null)
{
// topic: set priorities: 1. $topic, 2. environment NTFY_TOPIC, 3. throw exception
if ($topic) {
$this->topic = $topic;
}
if (!$this->topic && isset($_ENV['NTFY_TOPIC'])) {
$envTopic = $_ENV['NTFY_TOPIC'];
if ($envTopic) {
$this->topic = $envTopic;
}
}
$this->topic = $this->getValueFromEnv($topic, 'NTFY_TOPIC');
if ($this->topic === null) {
throw new Exception("Ntfy.sh topic must be set!");
}
// token: set priorities: 1. $token, 2. environment NTFY_TOKEN, 3. unset.
$this->token = $token;
if (!$this->token && isset($_ENV['NTFY_TOKEN'])) {
$envToken = $_ENV['NTFY_TOKEN'];
if ($envToken) {
$this->token = $envToken;
}
}
$this->token = $this->getValueFromEnv($token, 'NTFY_TOKEN');
// url: set priorities: 1. $serverUrl parameter, 2. environment NTFY_URL, 3. default url.
if (isset($_ENV['NTFY_URL'])) {
$envUrl = $_ENV['NTFY_URL'];
if ($envUrl) {
$this->serverUrl = $envUrl;
}
}
if ($serverUrl) {
$this->serverUrl = $serverUrl;
}
$url = $this->getValueFromEnv($serverUrl, 'NTFY_URL');
$this->serverUrl = $url ?? self::DEFAULT_URL;
}
public function publish(
string $title,
string $text,
@ -75,4 +57,15 @@ class Ntfy
]));
return $ret ? true : false;
}
private function getValueFromEnv(?string $value, string $envName): ?string
{
if (!$value && isset($_ENV[$envName])) {
$envValue = $_ENV[$envName];
if ($envValue) {
return $envValue;
}
}
return $value;
}
}