mercureact/src/Configuration.php

109 lines
2.7 KiB
PHP

<?php
namespace NoccyLabs\Mercureact;
use Symfony\Component\Yaml\Yaml;
class Configuration
{
private ?string $publicUrl = null;
private ?string $jwtSecret = null;
private bool $allowAnonymousSubscribe = false;
private array $listeners = [];
public static function createDefault(): Configuration
{
return new Configuration();
}
public static function fromFile(string $file): Configuration
{
$config = new Configuration();
$yaml = Yaml::parseFile($file);
if (isset($yaml['security'])) {
$security = $yaml['security'];
if (isset($security['jwt_secret']))
$config->setJwtSecret($security['jwt_secret']);
}
if (isset($yaml['subscribe'])) {
$subscribe = $yaml['subscribe'];
if (isset($subscribe['allow_anonymous']))
$config->setAllowAnonymousSubscribe(boolval($subscribe['allow_anonymous']));
}
if (isset($yaml['listeners'])) {
foreach ($yaml['listeners'] as $listener) {
if (!is_array($listener)) {
throw new \Exception("Bad listener config");
}
$config->addListener($listener);
}
}
return $config;
}
public function setPublicUrl(string $publicUrl): self
{
$this->publicUrl = $publicUrl;
return $this;
}
public function getPublicUrl(): ?string
{
return $this->publicUrl;
}
public function setJwtSecret(string $secret): self
{
$this->jwtSecret = $secret;
return $this;
}
public function getJwtSecret(): ?string
{
return $this->jwtSecret;
}
function getAllowAnonymousSubscribe():bool
{
return $this->allowAnonymousSubscribe;
}
function setAllowAnonymousSubscribe(bool $allowAnonymousSubscribe): self
{
$this->allowAnonymousSubscribe = $allowAnonymousSubscribe;
return $this;
}
function addListener(array $config): self
{
$this->listeners[] = [
'address' => $config['address']??throw new \Exception("Address can't be empty"),
'cors' => isset($config['cors'])?[
'allow_origin' => $config['cors']['allow_origin']??'*',
'csp' => $config['cors']['csp']??'default-src * \'self\'',
]:[
'allow_origin' => '*',
'csp' => 'default-src * \'self\'',
],
'websocket' => isset($config['websocket'])?[
'enable' => $config['websocket']['enable']??false
]:null,
];
return $this;
}
public function getListeners(): array
{
return $this->listeners;
}
}