Skip to content

Commit

Permalink
code tweaks
Browse files Browse the repository at this point in the history
  • Loading branch information
jannisnikoy committed Feb 21, 2024
1 parent 0daa858 commit 9dad0c9
Show file tree
Hide file tree
Showing 9 changed files with 59 additions and 32 deletions.
10 changes: 5 additions & 5 deletions src/Auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public function login(string $username, string $password): bool {
/**
* Deactives a user session and destroys the session object.
*/
public function logout() {
public function logout(): void {
$this->loggedIn = false;

if (Session::valueForKey('ATHOS_SESSION_ID')) {
Expand Down Expand Up @@ -164,7 +164,7 @@ private function attemptSessionLogin(): bool {
* @see attemptSessionLogin()
* @return bool true if a valid session is found.
*/
private function attemptCookieLogin() {
private function attemptCookieLogin(): bool {
if (isset($_COOKIE['athos']) && is_string($_COOKIE['athos'])) {
$s = json_decode($_COOKIE['athos'], true);

Expand Down Expand Up @@ -210,7 +210,7 @@ private function attemptLogin(string $username, string $password): bool {
* @return bool True if the session was validated
*/
private function validateSession(string $sessionId): bool {
$this->db->query('SELECT * FROM exm_sessions WHERE id=? AND expires_at > NOW() AND is_active=true', ...array($sessionId));
$this->db->query('SELECT * FROM exm_sessions WHERE id=? AND expires_at > NOW() AND is_active=true', ...[$sessionId]);

if ($this->db->hasRows()) {
$this->db->query('UPDATE exm_sessions SET last_updated_at=NOW() WHERE id=?', $sessionId);
Expand All @@ -228,11 +228,11 @@ private function validateSession(string $sessionId): bool {
*
* @param string $sessionId User session ID
*/
private function storeSessionData(string $sessionId) {
private function storeSessionData(string $sessionId): void {
Session::setValueForKey('ATHOS_SESSION_ID', $sessionId);

if ($this->shouldUseCookies()) {
$s = json_encode(array('ATHOS_SESSION_ID' => $sessionId));
$s = json_encode(['ATHOS_SESSION_ID' => $sessionId]);
setcookie('athos', $s, time()+$this->ttl);
}
}
Expand Down
20 changes: 13 additions & 7 deletions src/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,21 @@ public function __construct($configFile) {
}

$stage = $this->currentStage();
$this->stage = $stage;
$this->setupEnvironment($this->config->environments->$stage);

if(isset($stage)) {
$this->stage = $stage;
$this->setupEnvironment($this->config->environments->$stage);
} else {
echo '[ATHOS] Environment not found';
exit();
}
}

public function addModuleDir(string $directory) {
public function addModuleDir(string $directory): void {
array_push($this->config->module_dirs, $directory);
}

public function getEnvironmentVariable(string $key) {
public function getEnvironmentVariable(string $key): ?string {
$stage = $this->stage;

if(isset($this->config->environments->$stage->keys->$key)) {
Expand Down Expand Up @@ -79,7 +85,7 @@ public function get(string $key) {
// Private methods
//

private function setupEnvironment($environment) {
private function setupEnvironment($environment): void {
ini_set('display_errors', isset($environment->error_reporting) && $environment->error_reporting == true ? 1 : 0);
ini_set('error_reporting', isset($environment->error_reporting) && $environment->error_reporting == true ? E_ALL : E_ERROR | E_PARSE);

Expand All @@ -99,14 +105,14 @@ private function setupEnvironment($environment) {
*
* @return string environment name, or false if not found.
*/
public function currentStage() {
public function currentStage(): ?string {
foreach(array_keys(get_object_vars($this->config->environments)) as $environment) {
if (in_array($_SERVER['HTTP_HOST'], $this->config->environments->$environment->domains)) {
return $environment;
}
}

return false;
return null;
}
}
?>
2 changes: 1 addition & 1 deletion src/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,6 @@ public function requiresCredentials(): bool {
* @return array Array of accepted credentials
*/
public function acceptedCredentials(): array {
return array('admin');
return ['admin'];
}
}
4 changes: 2 additions & 2 deletions src/Database.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public function hasRows(): bool {
* @return array all results
*/
public function getRows(): array {
if (!$this->hasRows($this->result)) return array();
if (!$this->hasRows($this->result)) return [];

return $this->result;
}
Expand Down Expand Up @@ -132,7 +132,7 @@ private function connect(): bool {
/**
* Closes the database connection.
*/
private function disconnect() {
private function disconnect(): void {
$this->db->close();
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Files.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class Files {
* @return array Array of filenames
*/
public static function getFilesInDirectory(string $directory, string $extension = ''): array {
$files = array();
$files = [];

if (is_dir($directory) && $handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
Expand Down
35 changes: 28 additions & 7 deletions src/Logger.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
<?php

namespace Athos\Foundation;

use JsonException;

/**
* Logger
* Log REST requests and responses
Expand All @@ -19,14 +20,34 @@ class Logger {
* @param int $statusCode HTTP status code
* @param mixed $response Optional response payload
*/
public static function printOutput($statusCode, $response) {
public static function printOutput(int $statusCode, mixed $response = null): void {
global $db;

http_response_code($statusCode);
if(isset($response)) {
echo json_encode($response, isset($_GET['prettify']) && $_GET['prettify'] == 'true' ? JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT : JSON_NUMERIC_CHECK);

$options = JSON_NUMERIC_CHECK;
if (isset($_GET['prettify']) && $_GET['prettify'] === 'true') {
$options |= JSON_PRETTY_PRINT;
}

if($response != null) {
try {
$responseJson = json_encode($response, $options | JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
http_response_code(500);
echo json_encode(['error' => 'Failed to encode JSON'], JSON_THROW_ON_ERROR);
return;
}

echo $responseJson;
}

try {
$db->query("INSERT INTO exm_logs(status_code, method, ipaddress, path, headers, request, response) VALUES(?, ?, ?, ?, ?, ?, ?)", $statusCode, $_SERVER['REQUEST_METHOD'], $_SERVER['REMOTE_ADDR'], $_SERVER['REQUEST_URI'], json_encode(getallheaders()), file_get_contents('php://input'), json_encode($response));
} catch (Exception $e) {

}
$db->query("INSERT INTO exm_logs(status_code, method, ipaddress, path, headers, request, response) VALUES(?, ?, ?, ?, ?, ?, ?)", $statusCode, $_SERVER['REQUEST_METHOD'], $_SERVER['REMOTE_ADDR'], $_SERVER['REQUEST_URI'], json_encode(getallheaders()), file_get_contents('php://input'), json_encode($response));
}
}
?>
}

?>
6 changes: 3 additions & 3 deletions src/Module.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public function __construct() {
* @param string $moduleName Name of the module
* @param string $moduleAction Optional action to load within the module
*/
public function loadModule(string $moduleName, string $moduleAction = null) {
public function loadModule(string $moduleName, string $moduleAction = null): void {
$this->moduleName = $moduleName;
$this->moduleAction = $moduleAction;

Expand Down Expand Up @@ -109,7 +109,7 @@ private function moduleExists(): bool {
* @param string $moduleAction Optional action to load within the module
* @param bool $checkCredentials Allows for an override of credential checks
*/
private function loadController(string $moduleName, string $moduleAction = null, bool $checkCredentials = true) {
private function loadController(string $moduleName, string $moduleAction = null, bool $checkCredentials = true): void {
if(class_exists(ucfirst(isset($moduleAction) ? $moduleAction : $moduleName) . 'Controller')) {
$controller = ucfirst(isset($moduleAction) ? $moduleAction : $moduleName) . 'Controller';
$controller = new $controller();
Expand Down Expand Up @@ -142,7 +142,7 @@ private function loadController(string $moduleName, string $moduleAction = null,
/**
* Attempts to find the default controller and loads it if found.
*/
private function loadDefaultController() {
private function loadDefaultController(): void {
if(file_exists(SITE_PATH . '/modules/DefaultController.php')) {
require_once SITE_PATH.'/modules/DefaultController.php';
$this->loadController('Default', null, false);
Expand Down
8 changes: 4 additions & 4 deletions src/Session.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class Session {
* @param string $key
* @param $value
*/
public static function setValueForKey(string $key, $value) {
public static function setValueForKey(string $key, $value): void {
$_SESSION[$key] = $value;
}

Expand All @@ -43,7 +43,7 @@ public static function hasValueForKey(string $key): bool {
* @param string $key
* @return Value for provided key, or null if not found.
*/
public static function valueForKey(string $key) {
public static function valueForKey(string $key): ?string {
if (self::hasValueForKey($key)) {
return $_SESSION[$key];
}
Expand All @@ -56,14 +56,14 @@ public static function valueForKey(string $key) {
*
* @param string $key
*/
public static function removeValueForKey(string $key) {
public static function removeValueForKey(string $key): void {
unset($_SESSION[$key]);
}

/**
* Completely destroys the user session
*/
public static function destroySession() {
public static function destroySession(): void {
if (session_status() === PHP_SESSION_ACTIVE) {
session_destroy();
}
Expand Down
4 changes: 2 additions & 2 deletions src/Template.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public function __construct() {
* @param string $moduleName Name of the module -- Will be used as view name
* @param string $moduleAction Optional action name. View will override main view
*/
public function loadTemplate(string $viewDir, string $moduleName, string $moduleAction = null) {
public function loadTemplate(string $viewDir, string $moduleName, string $moduleAction = null): void {
if(file_exists($viewDir . $moduleAction . '.html')) {
$this->render($viewDir . $moduleAction . '.html');
} else if(file_exists($viewDir . $moduleName . '.html')){
Expand All @@ -45,7 +45,7 @@ public function loadTemplate(string $viewDir, string $moduleName, string $module
*
* @param string $file Full filename of the template to render
*/
private function render(string $file) {
private function render(string $file): void {
if(!file_exists($file)) {
return;
}
Expand Down

0 comments on commit 9dad0c9

Please sign in to comment.