You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

118 lines
2.3 KiB

<?php
namespace authkit2;
class Authkit2
{
const LIB_PREFIX = 'authkit2.';
protected $callbacks;
protected function __construct()
{
if (defined('LARAVEL_START'))
{
$this->initializeLaravel();
}
else
{
$this->initializeNative();
}
}
public static function get()
{
static $authkit2;
if (!isset($authkit2))
{
$authkit2 = new Authkit2();
}
return $authkit2;
}
public function __set(string $name, $value)
{
if (!array_key_exists($name, $this->callbacks))
{
trigger_error('Undefined property: '.__CLASS__.'::$'.$name, E_USER_WARNING);
return;
}
if (!is_callable($value))
{
throw new \Exception('Authkit2::'.$name.' value must be callable');
}
$this->callbacks[$name] = $value;
}
public static function __callStatic(string $name, array $arguments)
{
$authkit2 = static::get();
if (!isset($authkit2->callbacks[$name]))
{
trigger_error('Call to undefined method '.__CLASS__.'::'.$name.'()', E_USER_ERROR);
return;
}
return call_user_func_array($authkit2->callbacks[$name], $arguments);
}
protected function cache(string $key, callable $generator)
{
$value = static::cache_get($key, null);
if (!isset($value))
{
$value = $generator();
static::cache_set($key, $value);
}
return $value;
}
protected function initializeNative()
{
$this->callbacks = [
'session_get' => [$this, 'native_session_get'],
'session_set' => [$this, 'native_session_set'],
'cache_get' => [$this, 'native_cache_get'],
'cache_set' => [$this, 'native_cache_set'],
'cache' => [$this, 'cache']
];
}
protected function initializeLaravel()
{
throw new \Exception('TODO: Implement laravel support');
}
protected function native_session_get($key)
{
$this->native_session_check();
return $_SESSION[static::LIB_PREFIX.$key] ?? null;
}
protected function native_session_set($key, $value)
{
$this->native_session_check();
$_SESSION[static::LIB_PREFIX.$key] = $value;
}
protected function native_session_check()
{
if (session_status() == \PHP_SESSION_NONE)
session_start();
else if (session_status() == \PHP_SESSION_DISABLED)
throw new \Exception("Authkit2 requires PHP sessions are enabled");
}
protected function native_cache_get($key, $default = null)
{
return $default;
}
protected function native_cache_set($key, $value)
{
}
}