Port the old system to a more advanced setup.

This commit is contained in:
2019-03-03 16:16:31 +01:00
parent 04ae63035a
commit bfea8896de
14 changed files with 168 additions and 33 deletions

68
src/Configuration.php Normal file
View File

@@ -0,0 +1,68 @@
<?php
namespace FooBar;
/**
* Main configuration class.
*
* Reads the app configuration from an array (or optionally a file via loadConfig) and provide easy access.
*/
class Configuration
{
private $address;
private $mask;
private $stateFile;
public function __construct(array $config)
{
$this->address = $config['security']['address'];
$this->mask = $config['security']['mask'];
$this->stateFile = $config['state_file'];
}
public static function loadConfig(): Configuration
{
$options = [
dirname(__DIR__) . '/config/config.php',
dirname(__DIR__) . '/config/config.sample.php',
];
foreach ($options as $option) {
if (file_exists($option)) {
return new Configuration(require $option);
}
}
throw new \RuntimeException('Couldn\'t find config file');
}
/**
* Check if the user is authorized to do a toggle.
*
* @param string|null $address An IP-address, or null to default to the clients address.
* @return bool true if the user should be allowed.
*/
public function isAuthorized($address = null): bool
{
$address = ip2long($address ?? $_SERVER['REMOTE_ADDR']);
$allowed = ip2long($this->address);
if ($this->mask >= 32) {
return $address === $allowed;
}
$shift = 32 - $this->mask;
return ($address >> $shift) === ($allowed >> $shift);
}
public function stateFile(): string
{
return $this->stateFile;
}
public function isOpen(): bool
{
return file_exists($this->stateFile);
}
}