Skip to content

Commit

Permalink
Clean source code
Browse files Browse the repository at this point in the history
  • Loading branch information
vgalvoso committed Feb 19, 2024
1 parent ebfe9bf commit 008cd86
Show file tree
Hide file tree
Showing 16 changed files with 291 additions and 122 deletions.
9 changes: 7 additions & 2 deletions .htaccess
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
RewriteEngine On
# Redirect Trailing Slashes...

# Redirect Trailing Slashes for GET requests...
RewriteCond %{REQUEST_METHOD} =GET
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
RewriteRule ^ %1 [L,R=301]

# Route requests to index.php...
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\s\S]*)$ index.php/$1 [L,NC,QSA]

Options -Indexes
7 changes: 6 additions & 1 deletion Core/Config.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
<?php

namespace Core\Config;

/**
* This file contains essential configurations for the entire project.
*/
Expand All @@ -7,4 +10,6 @@

//CONSTANTS
define('CURRENT_DATETIME',date("Y-m-d H:i:s"));
define('CURRENT_DATE',date("Y-m-d"));
define('CURRENT_DATE',date("Y-m-d"));

//EOF
35 changes: 28 additions & 7 deletions Core/DAL.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
<?php

namespace Core;

use PDO;
use PDOException;
use function Core\Helper\output;

class DAL{

protected $conn;
Expand All @@ -9,15 +16,29 @@ class DAL{
*
* @author Van
*/
public function __construct(){
$server = getenv('DB_HOST');
$user = getenv('DB_USER');
$pass = getenv('DB_PASS');
$dbname = getenv('DB_NAME');
$driver = getenv('DB_DRIVER');
public function __construct($dbase = "default"){
require "Database.php";
$database = $db[$dbase] ?? null;
if($database == null){
$data = ["status"=>"Failed","message"=>"Database config [$dbase] not found"];
output($data);
}
$server = $db[$dbase]["server"];
$user = $db[$dbase]["user"];
$pass = $db[$dbase]["pass"];
$dbname = $db[$dbase]["dbname"];
$driver = $db[$dbase]["driver"];
$charset = $db[$dbase]["charset"];

try{
$this->conn = new PDO("$driver:host=$server;dbname=$dbname;",$user,$pass,
if($driver=="sqlsrv"){
$this->conn = new PDO("$driver:Server=$server;database=$dbname;Encrypt=true;TrustServerCertificate=true;",$user,$pass,
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
}
if($driver=="mysql"){
$this->conn = new PDO("$driver:host=$server;dbname=$dbname;charset=$charset",$user,$pass,
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
}
}catch(PDOException $e){
exit($this->error = $e);
}
Expand Down
19 changes: 19 additions & 0 deletions Core/Database.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php
$db = [
"default" => [
"server" => "localhost",
"user" => "root",
"pass" => "",
"dbname" => "phpeasy_db",
"driver" => "mysql",
"charset" => "utf8"
],
"ms_local" => [
"server" => "LAPTOP-Q8NP2H0P\SQLEXPRESS",
"user" => "",
"pass" => "",
"dbname" => "srspos",
"driver" => "sqlsrv",
"charset" => "utf8"
]
];
118 changes: 96 additions & 22 deletions Core/Helper.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
<?php

namespace Core\Helper;

readDotEnv();
init();
function readDotEnv(){
$envPath = BASE_DIR.'/.env';
$envPath = dirname(__DIR__).'/.env';
$lines = file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
if (strpos(trim($line), '#') === 0)
Expand All @@ -19,6 +22,7 @@ function readDotEnv(){
}
}
function init(){
$method = "";
if(isset($_SERVER['REQUEST_URI'])){
$path = $_SERVER['REQUEST_URI'];
//get $path except first "/"
Expand Down Expand Up @@ -51,12 +55,12 @@ function post(){
* Declare a php file as an HTTP GET endpoint
*/
function get(){
if(REQUEST_METHOD != "GET")
notFound();
if(isset($_SESSION["in_script"]) && session("in_script")){
session("in_script",false);
return true;
}
if(REQUEST_METHOD != "GET")
notFound();
}

/**
Expand Down Expand Up @@ -88,8 +92,12 @@ function objectToSession($object){
}

function notFound(){
header("HTTP/1.1 404 Not Found");
die("URL not found");
$errData = [
"status" => "failed",
"code" => 404,
"error" => "Resource not found!"
];
response($errData,404);
}

/**
Expand All @@ -100,16 +108,35 @@ function esc($string){
}

/**
* Set content type then output content and exit script
* @param string $content The content to output
* @param string $contentType The content type (default application/json)
* Enclose value of array items with specified character
* @param array $arr|indexed Array containing items to enclose
* @param string $char Character to be use as enclosure
* @return array
*/
function output($content,$contentType = 'application/json'){
function encloseItems($arr,$char = "'"){
foreach($arr as &$item):
$item = $char.$item.$char;
endforeach;
return $arr;
}

/**
* Set content type and status code then output content and exit script
* @param string|array $content The content to output
* @param int $statusCode The response status code (default 200)
* @param string $contentType The content type (default application/json).
* Available content-types: [ application/json | plain/text | text/html ]
* @return void
*/
function response(string|array $content,int $statusCode = 200,string $contentType = 'application/json',){
header("Content-Type: $contentType");
http_response_code($statusCode);
$data = match ($contentType) {
"application/json" => json_encode($content)
"application/json" => json_encode($content),
"plain/text" => json_encode($content),
"text/html" => $content
};
die($data);
exit($data);
}

/**
Expand Down Expand Up @@ -187,11 +214,19 @@ function session($sessionVar, $value = null){
function objArrayToValues($objArr,$item){
$arr = [];
foreach($objArr as $obj){
$obj = (object)$obj;
array_push($arr, $obj->$item);
}
return $arr;
}

/**
* Check wether the path provided in request is view or an api.
* If view includes the specified view,
* if not, returns false.
*
* @return void|false
*/
function view(){
if(PATH == ""){
include "View/index.php";
Expand All @@ -213,24 +248,63 @@ function view(){
die;
}

/**
* State that a php view file is an SPA component.
* This function will prevent the view file to be accessible via url,
* can only be accessed through ajax call
*/
function component(){
if(isset($_SERVER["HTTP_SEC_FETCH_MODE"]) && ($_SERVER["HTTP_SEC_FETCH_MODE"] == "navigate"))
notFound();
}

/**
* Check wether the path provided in request is an api or a view.
* If api, includes the specified api,
* if not, returns false.
*
* @return void|false
*/
function api(){
if(isset($_SERVER["HTTP_SEC_FETCH_MODE"]) && ($_SERVER["HTTP_SEC_FETCH_MODE"] == "navigate"))
notFound();
//get all after "api/"
$rawPath = substr(PATH,4);
//remove query params so raw resource uri remains eg. [users?city='caloocan'] to [users]
$rawPath = strstr($rawPath, "?", true) ?: $rawPath;
//check if has uri param
$parts = explode("/",rtrim($rawPath,"/"));
if(count($parts) > 1):
$rawPath = $parts[0];
//extract the uri param
define("URI_PARAM",$parts[1]);
endif;
$rawPath = rtrim($rawPath,"/");
if(!file_exists("api/$rawPath.php"))
if(!file_exists("api/$rawPath/index.php"))
return false;
else
$rawPath .= "/index";

if(!empty($_GET))
extract($_GET);

notFound();
include "api/$rawPath.php";
die;
}
}

/**
* Starts a php file as a REST API
*/
function startAPI(){
if(function_exists(strtolower(REQUEST_METHOD)))
strtolower(REQUEST_METHOD)();
else
response(["status" => "failed","error" =>"Method Not Allowed!"],405);
}

/**
* Decode JSON string from request body [file_get_contents("php://input")]
* into associative array, exit and return 403 status code with message
* "Invalid json data" if fail
* @return array
*/
function getRequestBody(){
$data = file_get_contents("php://input");
if(!$data = json_decode($data,true))
response("Invalid json data");
return $data;
}

//EOF
42 changes: 13 additions & 29 deletions Core/Validator.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
<?php

namespace Core\Validator;

use function Core\Helper\response;

/**
* if not valid, echo errors and exit script, return true if valid
* Validate inputs, return true if valid,
* exit and return 400 status code and error details if not
* @param array $inputs Array of variables to be validated
* @param array $validations Array of validation rules
* @return boolean
*/
function validate($inputs, $validations) {
$errors = [];
Expand Down Expand Up @@ -66,35 +73,12 @@ function validate($inputs, $validations) {
}
if (!empty($errors)) {
// Handle validation errors
http_response_code(403);
foreach ($errors as $field => $fieldErrors) {
foreach ($fieldErrors as $error) {
echo "<p>$error</p><br>";
}
}
$data = [
"status" => "Failed",
"error(s):" => array_reduce($errors,'array_merge',[])
];
response($data,400);
exit();
}
return true;
//return $errors;
}

/**
* Return 403 response code to mark as invalid
* @param string $message Error message to show
*/
function invalid($message){
http_response_code(403);
exit($message);
}

/**
* Place specified inputs from GET/POST to an array
*/
function allowedVars($inputs,$rules){
$vars = [];
foreach($inputs as $key => $val)
foreach($rules as $ruleKey => $ruleVal)
if($key ==$ruleKey)
$vars[$key]=$val;
return $vars;
}
23 changes: 15 additions & 8 deletions Models/Model.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
<?php

namespace Models;

use Core\DAL;

class Model{

protected $db;
Expand All @@ -8,21 +13,23 @@ protected function __construct(DAL $db){
$this->db = $db;
}

public function getAll(){
$sql = "SELECT * FROM $this->table";
return $this->db->getItems($sql);
}

public function create($values){
return $this->db->insert($this->table,$values);
public function getAll(string $condition = "1=1",array $params = []){
$sql = "SELECT * FROM $this->table WHERE $condition";
return $this->db->getItems($sql,$params);
}

public function get($id){
$sql = "SELECT * FROM $this->table WHERE id=:id";
return $this->db->getItem($sql,["id" => $id]);
}

public function add($values){
return $this->db->insert($this->table,$values);
}

public function delete($id){
return $this->db->delete($this->table,"id=:id",["id"=>$id]);
}
}
}

//EOF
Loading

0 comments on commit 008cd86

Please sign in to comment.