rework structure

added Router
added .htaccess
removed API-Module => is not used
renamed batch to CRON
This commit is contained in:
Maurice Grönwoldt 2020-09-10 22:47:58 +02:00
commit c33bb4cb3a
23 changed files with 677 additions and 187 deletions

View file

@ -0,0 +1,42 @@
<?php
namespace Venom\Core;
class ArgumentHandler
{
public static ?ArgumentHandler $instance = null;
private array $arguments = [];
public function __construct()
{
foreach ($_GET as $key => $item) {
$this->arguments[htmlspecialchars($key)] = htmlspecialchars($item);
}
foreach ($_POST as $key => $item) {
$this->arguments[htmlspecialchars($key)] = htmlspecialchars($item);
}
}
public static function get(): ArgumentHandler
{
if (self::$instance === null) {
self::$instance = new ArgumentHandler();
}
return self::$instance;
}
public function getItem(string $key, $default = null)
{
if (isset($this->arguments[$key])) {
return $this->arguments[$key];
}
return $default;
}
public function setItem(string $key, $item)
{
$this->arguments[$key] = $item;
}
}

181
src/Venom/Core/Config.php Normal file
View file

@ -0,0 +1,181 @@
<?php
namespace Venom\Core;
use Venom\Models\ConfigObject;
class Config
{
private static ?Config $instance = null;
private bool $isWriteable = true;
private float $version = 1.0;
private ConfigObject $mail;
private ConfigObject $renderer;
private ConfigObject $security;
private bool $maintenance = false;
private bool $devMode = false;
private bool $isAdmin = false;
private string $baseUrl = '';
private bool $seoMode = false;
private bool $useRouter = false;
private function __construct()
{
$this->mail = new ConfigObject();
$this->renderer = new ConfigObject();
$this->security = new ConfigObject();
}
public static function getInstance(): Config
{
if (self::$instance === null) {
self::$instance = new Config();
}
return self::$instance;
}
public function setDatabase(array $array): void
{
if ($this->isWriteable) {
DatabaseHandler::get()->init($array);
} else {
trigger_error('try to write closed config!');
}
}
public function setRender(array $array): void
{
$this->set('renderer', $array);
}
public function set(string $variable, $value): void
{
if (!$this->isWriteable) {
trigger_error('try to write closed config!');
return;
}
if ($this->$variable instanceof ConfigObject) {
$this->$variable->setData($value);
} else {
$this->$variable = $value;
}
}
public function setMaintainMode(bool $mode): void
{
$this->set('maintenance', $mode);
}
public function getVersion(): float
{
return $this->version;
}
public function setVersion(float $param): void
{
$this->set('version', $param);
}
public function getMail(): ConfigObject
{
return $this->mail;
}
public function setMail(array $array): void
{
$this->set('mail', $array);
}
public function getRenderer(): ConfigObject
{
return $this->renderer;
}
public function isMaintenance(): bool
{
return $this->maintenance;
}
public function isDevMode(): bool
{
return $this->devMode;
}
public function setDevMode(bool $mode): void
{
$this->set('devMode', $mode);
}
/**
* @return bool
*/
public function isAdmin(): bool
{
return $this->isAdmin;
}
/**
* @param bool $isAdmin
*/
public function setIsAdmin(bool $isAdmin): void
{
$this->set('isAdmin', $isAdmin);
}
public function setSeoMode(bool $mode): void
{
$this->set('seoMode', $mode);
}
public function getSeoEnabled(): bool
{
return $this->seoMode;
}
/**
* @return bool
*/
public function isClosed(): bool
{
return !$this->isWriteable;
}
/**
* function to close the write mode... this make sure after the config is init no other tool can write to it!
*/
public function close(): void
{
$this->isWriteable = false;
}
public function getBaseUrl(): string
{
return $this->baseUrl;
}
public function setBaseUrl(string $url): void
{
$this->set('baseUrl', $url);
}
public function getSecurity(): ConfigObject
{
return $this->security;
}
public function setSecurity(array $security): void
{
$this->set('security', $security);
}
public function setEnableRouter(bool $value): void
{
$this->set('useRouter', $value);
}
public function isRouterEnabled(): bool
{
return $this->useRouter;
}
}

View file

@ -0,0 +1,74 @@
<?php
namespace Venom\Core;
use PDO;
use PDOException;
use Venom\Models\DatabaseObject;
/**
* Singleton DatabaseHandler... make sure we only have one connection to the database..
* @package Venom\Database
*/
class DatabaseHandler
{
// constants
public const DB_TYPE = 'type';
public const DB_HOST = 'host';
public const DB_PORT = 'port';
public const DB_USER = 'user';
public const DB_PASSWORD = 'pw';
public const DB_DB = 'db';
public const DB_EXTRA = 'extra';
private static ?self $instance = null;
private ?PDO $db = null;
public static function get(): DatabaseHandler
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
public function init(array $data): void
{
//init instance with the current data... only working if the db is not init!
if ($this->db != null) {
return;
}
$dsn = '%s:host=%s;dbname=%s;port=%s';
$connectString = sprintf($dsn, $data[self::DB_TYPE], $data[self::DB_HOST], $data[self::DB_DB], $data[self::DB_PORT] . $data[self::DB_EXTRA]);
try {
$this->db = new PDO($connectString, $data[self::DB_USER], $data[self::DB_PASSWORD]);
} catch (PDOException $e) {
trigger_error($e->getMessage());
die($e->getCode());
}
}
public function getOne(string $query, array $args): ?DatabaseObject
{
$data = $this->getAll($query, $args);
if (count($data) > 0) {
return $data[0];
}
return null;
}
public function getAll(string $query, array $args): array
{
$stmt = $this->db->prepare($query);
$stmt->setFetchMode(PDO::FETCH_CLASS, DatabaseObject::class);
$stmt->execute($args);
return $stmt->fetchAll();
}
public function execute(string $query, array $args): void
{
$stmt = $this->db->prepare($query);
$stmt->execute($args);
}
}

View file

@ -0,0 +1,61 @@
<?php
namespace Venom\Core;
use RuntimeException;
use Venom\Models\DatabaseObject;
class Language
{
private string $language = "";
private array $languages = [];
private ?DatabaseObject $defaultLang;
public function __construct()
{
$this->defaultLang = DatabaseHandler::get()->getOne("select language, shortTag from language WHERE isActive = 1 and isDefault = 1", []);
}
public function initLang()
{
$lang = ArgumentHandler::get()->getItem("lang", $this->defaultLang->shortTag);
//check if language exists
$data = DatabaseHandler::get()->getOne("select id from language where shortTag = :shortTag", [
':shortTag' => $lang
]);
if (isset($data->id)) {
$this->language = $lang;
} else {
throw new RuntimeException("Language \"$lang\" not found");
}
}
public function registerLang(string $key, array $values)
{
$this->languages[$key] = $values;
}
public function getCurrentLang()
{
return $this->language;
}
public function getTranslations()
{
return $this->languages[$this->language] ?: [];
}
public function getTranslation($key)
{
if (!isset($this->languages[$this->language])) {
return $key;
}
if (isset($this->languages[$this->language][$key])) {
return $this->languages[$this->language][$key];
}
return $key;
}
}

12
src/Venom/Core/Module.php Normal file
View file

@ -0,0 +1,12 @@
<?php
namespace Venom\Core;
interface Module
{
public function register(): bool;
public function init(): void;
}

View file

@ -0,0 +1,41 @@
<?php
namespace Venom\Core;
use Venom\Routing\SeoController;
/**
* Singleton Class... hold current URL => can
* @package Venom
*/
class Registry
{
private static ?Registry $instance = null;
private SeoController $seo;
private Language $lang;
private function __construct()
{
$this->seo = new SeoController();
$this->lang = new Language();
}
public static function getInstance(): Registry
{
if (self::$instance === null) {
self::$instance = new Registry();
}
return self::$instance;
}
public function getSeo(): SeoController
{
return $this->seo;
}
public function getLang(): Language
{
return $this->lang;
}
}

58
src/Venom/Core/Setup.php Normal file
View file

@ -0,0 +1,58 @@
<?php
namespace Venom\Core;
use Venom\Venom;
class Setup
{
public static function loadConfig(bool $isAdmin): void
{
$config = Config::getInstance();
$config->setIsAdmin($isAdmin);
$file = self::tryLoading('config.inc.php', 'config.base.php', "Config");
require $file;
}
public static function tryLoading(string $file, string $baseFile, string $type): string
{
$newFile = __DIR__ . '/../../../conf/' . $file;
if (!file_exists($newFile)) {
$newBaseFile = __DIR__ . '/../../../base/' . $baseFile;
if (copy($newBaseFile, $newFile)) {
echo 'Created File for: ' . $type . '! Please Adjust the file';
} else {
echo 'Cannot create File for: ' . $type . '!';
}
exit(1);
}
return $newFile;
}
public static function loadModules(Venom $venom): void
{
$file = self::tryLoading('modules.inc.php', 'module.base.php', "Modules");
require $file;
if (isset($modules)) {
$venom->initModules($modules);
}
if (isset($controllers)) {
$venom->initControllers($controllers);
}
}
public static function loadRouters(Venom $venom): void
{
$file = self::tryLoading('routers.inc.php', 'router.base.php', "Routers");
require $file;
}
public static function loadLanguage(): void
{
$file = self::tryLoading('lang.inc.php', 'lang.base.php', "Languages");
require $file;
}
}

View file

@ -0,0 +1,48 @@
<?php
namespace Venom\Exceptions;
use Exception;
use Throwable;
class ExceptionHandler
{
private string $logFile = __DIR__ . '/../../../logs/Exception.log';
private $file;
public function __construct()
{
try {
$this->file = fopen($this->logFile, 'ab+');
} catch (Throwable $ex) {
$this->file = null;
}
}
public static function setExceptionHandler(): void
{
set_exception_handler(array(__CLASS__, 'handleException'));
}
public static function handleException(Throwable $ex): void
{
$handler = new ExceptionHandler();
$handler->writeException($ex);
exit(255);
}
public function writeException(Throwable $ex): void
{
if ($this->file !== null) {
try {
$trace = "=====[FATAL ERROR]=====\n" . $ex->getMessage() . "\n" . $ex->getTraceAsString() . "\n=====[FATAL ERROR END]=====\n";
fwrite($this->file, $trace);
fclose($this->file);
} catch (Exception $e) {
trigger_error("cannot write Exception file!");
}
}
}
}

View file

@ -0,0 +1,35 @@
<?php
namespace Venom\Helper;
use Venom\Core\ArgumentHandler;
class ErrorHandler
{
public static function setFatalError(): void
{
self::setError(500);
}
public static function setNotFound(): void
{
self::setError(404);
}
public static function setNoContent(): void
{
self::setError(204);
}
public static function setError(int $errorCode): void
{
http_response_code($errorCode);
ArgumentHandler::get()->setItem('cl', 'error');
ArgumentHandler::get()->setItem('fnc', 'handleError');
ArgumentHandler::get()->setItem('errorCode', $errorCode);
}
}

View file

@ -0,0 +1,14 @@
<?php
namespace Venom\Helper;
/**
* Class MetaGenerator
* @package Venom\Helper
*/
class MetaGenerator
{
}

View file

@ -0,0 +1,45 @@
<?php
namespace Venom\Helper;
class URLHelper
{
private static ?URLHelper $instance = null;
private string $parsedUrl;
public function __construct()
{
$this->parsedUrl = htmlspecialchars(parse_url($_SERVER['REQUEST_URI'])['path']);
}
public static function getInstance(): URLHelper
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
public function getUrl(): string
{
return $this->parsedUrl;
}
public function getUrlForId($id): string
{
return '';
}
public function getUrlForController($cl): string
{
return '';
}
public function generateFullUrl($url): string
{
return $url;
}
}

View file

@ -0,0 +1,38 @@
<?php
namespace Venom\Models;
class ConfigObject
{
private array $data = [];
public function __get($name)
{
if (isset($this->data[$name])) {
return $this->data[$name];
}
return null;
}
public function __set($name, $value)
{
$this->data[$name] = $value;
}
public function __isset($name)
{
return isset($this->data[$name]);
}
public function setData(array $data): void
{
$this->data = $data;
}
public function toString(): string
{
return implode(';', $this->data);
}
}

View file

@ -0,0 +1,44 @@
<?php
namespace Venom\Models;
/**
* Database Object to use queries like this $obj->id, $obj->value
* also the option to print it in csv format ; as delimiter
* @package Venom\Database
*/
class DatabaseObject
{
private array $data = [];
public function __get($name)
{
if (isset($this->data[$name])) {
return $this->data[$name];
}
return null;
}
public function __set($name, $value)
{
$this->data[$name] = $value;
}
public function __isset($name)
{
return isset($this->data[$name]);
}
public function toString()
{
return implode(';', $this->data);
}
public function getHead()
{
$keys = array_keys($this->data);
return implode(';', $keys);
}
}

14
src/Venom/Models/User.php Normal file
View file

@ -0,0 +1,14 @@
<?php
namespace Venom\Models;
class User
{
private string $username;
private string $password;
private string $salt;
private string $token;
private array $roles;
}

View file

@ -0,0 +1,10 @@
<?php
namespace Venom\Routing;
interface Route
{
}

View file

@ -0,0 +1,111 @@
<?php
namespace Venom\Routing;
use Exception;
class Router
{
protected string $id = 'defaultRouter';
protected int $version;
protected string $prefix = '';
protected array $routes = [];
public function __construct(string $id, int $version, string $prefix = '')
{
$this->id = $id;
$this->version = $version;
$this->prefix = $prefix;
}
public function addRoutes(array $routes): void
{
$this->routes = $routes;
}
public function addRoute(string $path, array $route): void
{
$this->routes[$path] = $route;
}
/*
* return matched route or null
*/
public function findRoute($url, $method): ?array
{
$url = $this->removeIfFirst($url, $this->prefix);
// check if full match... this can easily done if the url isset select the empty!
$method = strtoupper($method);
$route = $this->getRouteByName($url, $method);
if ($route !== null) {
return $route;
}
$url = $this->removeIfFirst($url, '/');
$baseRoute = $this->getNearestBaseRoute(explode("/", $url));
if ($baseRoute !== null) {
$count = count($baseRoute['params']);
return $this->getRouteByName($baseRoute['url'], $method, $count, $baseRoute['params']) ?? $this->getRouteByName($baseRoute['url'], $method);
}
return null;
}
private function removeIfFirst($rawString, $string)
{
if ($string !== '' && 0 === strpos($rawString, $string)) {
return substr($rawString, strlen($string));
}
return $rawString;
}
/* @todo implement Security Check if SecurityModule is used */
private function getRouteByName($url, $method, $subRoute = '*', $params = []): ?array
{
$routeAvailable = isset($this->routes[$url]);
$subRouteFound = isset($this->routes[$url]['routes'][$subRoute]);
$methodFound = isset($this->routes[$url]['routes'][$subRoute][$method]);
if ($routeAvailable && $subRouteFound && $methodFound) {
return [
'cl' => $this->routes[$url]['cl'],
'fnc' => $this->routes[$url]['routes'][$subRoute][$method],
'params' => $params
];
}
return null;
}
private function getNearestBaseRoute(array $params): ?array
{
$count = count($params);
$baseUrlArray = [];
$newParams = [];
foreach ($params as $value) {
$baseUrlArray[] = $value;
}
for ($i = 0; $i < $count; $i++) {
$newParams[] = array_pop($baseUrlArray);
$url = '/' . implode('/', $baseUrlArray);
if (isset($this->routes[$url])) {
return ['url' => $url, 'params' => $newParams];
}
}
return null;
}
public function tryFunctionCall(?array $aRoute): bool
{
if ($aRoute === null || !is_callable(array($aRoute['cl'], $aRoute['fnc']))) {
return false;
}
$route = new $aRoute['cl']();
try {
$fnc = $aRoute['fnc'];
$params = $aRoute['params'] ?? [];
$route->$fnc(...$params);
return true;
} catch (Exception $ex) {
return false;
}
}
}

View file

@ -0,0 +1,58 @@
<?php
namespace Venom\Routing;
use Venom\Core\ArgumentHandler;
use Venom\Core\Config;
use Venom\Core\DatabaseHandler;
use Venom\Helper\ErrorHandler;
use Venom\Helper\URLHelper;
class SeoController
{
private bool $shouldUse;
private $data = null;
public function __construct()
{
$this->shouldUse = Config::getInstance()->getSeoEnabled();
}
public function loadSite(): void
{
if (!$this->shouldUse) {
return;
}
$url = URLHelper::getInstance()->getUrl();
$data = DatabaseHandler::get()->getOne("SELECT * FROM seoData WHERE seo = :url", [
':url' => $url,
]);
$this->data = $data;
if ($this->data !== null) {
parse_str(parse_url($this->data->raw)['query'], $queryItems);
foreach ($queryItems as $key => $item) {
ArgumentHandler::get()->setItem($key, $item);
}
} else {
ErrorHandler::setNotFound();
}
}
public function addSite(): void
{
}
public function deleteSite(): void
{
}
public function getData()
{
return $this->data;
}
}

View file

@ -0,0 +1,13 @@
<?php
namespace Venom\Security;
/**
* Class that Login stupid via Password, Username
*/
class BaseLogin
{
}

View file

@ -0,0 +1,22 @@
<?php
namespace Venom\Security;
use Venom\Models\User;
interface Login
{
public function __construct(User $user);
public function checkUsername(): bool;
public function checkPassword(): bool;
public function checkCredentials(): bool;
public function login(): bool;
public function redirect(): void;
}

View file

@ -0,0 +1,31 @@
<?php
namespace Venom\Security;
class Security
{
private static ?Security $instance = null;
public static function get(): Security
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/* @todo implement logic */
public function hasRole(string $role): bool
{
return true;
}
/* @todo implement logic */
public function hasRoles(array $roles): bool
{
return true;
}
}

Some files were not shown because too many files have changed in this diff Show more