Skip to content

Commit

Permalink
Merge pull request #203 from kivudesign/router_refactoring
Browse files Browse the repository at this point in the history
[ENH] Refactoring routing for more flexibility
  • Loading branch information
bim-g authored Sep 22, 2024
2 parents 06d71ff + 16b122b commit 82e31b1
Show file tree
Hide file tree
Showing 16 changed files with 362 additions and 142 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
use Wepesi\Core\Http\Redirect;
use Wepesi\Core\Session;

class indexController extends Controller
class exampleController extends Controller
{
public function __construct()
{
Expand Down
4 changes: 1 addition & 3 deletions index.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
(new DotEnv($ROOT_DIR . '/.env'))->load();

/**
* Generate and index file for redirection (protection) while APP_DEV in production
* Generate and index a file for redirection (protection) while APP_DEV in production
*/
if (getenv('APP_ENV') === 'prod') {
autoIndexFolder(['assets']);
Expand All @@ -31,6 +31,4 @@

$app = new Application($ROOT_DIR, $configuration);

require_once $app::$ROOT_DIR . '/router/route.php';

$app->run();
6 changes: 0 additions & 6 deletions router/api.php

This file was deleted.

10 changes: 10 additions & 0 deletions routes/api.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

global $app;

use Wepesi\Core\Http\Response;

$router = $app->router();
$router->get('/', function () {
Response::send('Welcome to Wepesi API');
});
17 changes: 13 additions & 4 deletions router/route.php → routes/web.php
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
<?php
/*
* Copyright (c) 2024. Wepesi Dev Framework
*/
global $app;

use Wepesi\Controller\indexController;
use Wepesi\Controller\exampleController;
use Wepesi\Core\Http\Response;
use Wepesi\Core\Views\View;
use Wepesi\Middleware\Validation\exampleValidation;

$router = $app->router();

// setup get started pages index
$router->get('/', function () {
(new View)->display('/home');
Expand All @@ -13,9 +19,12 @@
$router->get('/helloworld', function () {
(new View)->renderHTML('<h1>Hello World!</h1>');
});
$router->get('/home', [\Wepesi\Controller\indexController::class,'home']);

$router->get('/home', [exampleController::class,'home']);
//
$router->post('/changelang', [indexController::class, 'changeLang'])
$router->post('/changelang', [exampleController::class, 'changeLang'])
->middleware([exampleValidation::class, 'changeLang']);

include \Wepesi\Core\Application::$ROOT_DIR . './router/api.php';
$router->set404(function(){
Response::send('route not defined', 404);
});
173 changes: 116 additions & 57 deletions src/Core/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,99 +12,77 @@
*/
class Application
{
/**
* @var array
*/
private static array $config_params = [];
/**
* define application global configuration
* @var string
*/
public static string $ROOT_DIR;
private static string $root_dir;
/**
* @var string
*/
public static string $APP_DOMAIN;
/**
* @var string|mixed
* @var string
*/
public static string $APP_LANG;
/**
* @var string|mixed|null
*/
public static ?string $APP_TEMPLATE;
/**
* @var string
*/
private static string $LAYOUT_CONTENT = 'layout_content';
public static string $APP_TEMPLATE;
/**
* @var string
*/
private static string $LAYOUT = '';
public static string $layout_content_param;
/**
* @var string
*/
private static string $VIEW_FOLDER = '';
private static string $layout;

/**
* @var array
* @var string
*/
private static array $params = [];
private static string $VIEW_FOLDER;
/**
* @var Router
*/
private Router $router;

/**
* Application constructor.
* @param string $path path root directory of the application
* @param string $path root path directory of the application
* @param AppConfiguration $config
*/
public function __construct(string $path, AppConfiguration $config)
{

self::$ROOT_DIR = str_replace("\\", '/', $path);
self::$APP_DOMAIN = $this->domainSetup()->app_domain;
self::$params = $config->generate();
self::$APP_TEMPLATE = self::$params['app_template'] ?? null;
self::$APP_LANG = self::$params['lang'] ?? 'fr';
self::$config_params = $config->generate();
self::$root_dir = str_replace("\\", '/', $path);
self::$APP_DOMAIN = serverDomain()->domain;
self::$APP_LANG = self::$config_params['lang'] ?? 'fr';
self::$APP_TEMPLATE = self::$config_params['app_template'] ?? '';
self::$layout_content_param = 'layout_content';
self::$layout = '';
self::$VIEW_FOLDER = '';
$this->router = new Router();
self::$LAYOUT_CONTENT = 'layout_content';
}

/**
* @return object
*/
private function domainSetup(): object
{
$server_name = $_SERVER['SERVER_NAME'];
$protocol = strtolower(explode('/', $_SERVER['SERVER_PROTOCOL'])[0]);
$domain = self::getDomainIp() === '127.0.0.1' ? "$protocol://$server_name" : $server_name;
return (object)[
'server_name' => $server_name,
'protocol' => $protocol,
'app_domain' => $domain,
];
}

/**
* use method to get domain ip
* @return string
*/
public static function getDomainIp() : string
public static function getRootDir(): string
{
$ip = $_SERVER['REMOTE_ADDR'];

if (! empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (! empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif ($ip == '::1') {
$ip = gethostbyname(getHostName());
}
return $ip;
return self::$root_dir;
}

/**
* simple builtin dumper for dump data
* @param $ex
* @return void
*
*/
public static function dumper($ex)
public static function dumper($ex): void
{
print('<pre>');
var_dump($ex);
Expand All @@ -113,32 +91,53 @@ public static function dumper($ex)
}

/**
* Set the layout at the top of your application to be available everywhere.
* Define a layout to be used by all pages in the application.
* can be set at the top of your application to be available everywhere.
* @param string $layout
* @return void
*/
public static function setLayout(string $layout)
{
self::$LAYOUT = self::$ROOT_DIR.'/views/'.$layout;
self::$layout = self::getRootDir() . '/views/' . trim($layout, '/');
}
public static function setLayoutContent(string $layout_name)

/**
* @param string $layout_name
* @return void
*/
public static function setLayoutcontentparam(string $layout_name)
{
self::$LAYOUT_CONTENT = $layout_name;
self::$layout_content_param = $layout_name;
}

/**
* @param string $folder_name
* @return void
*/
public static function setViewFolder(string $folder_name)
{
self::$VIEW_FOLDER = $folder_name;
}
public static function getLayout()

/**
* @return string
*/
public static function getLayout(): string
{
return self::$LAYOUT ;
return trim(self::$layout );
}
public static function getLayoutContent()

/**
* @return string
*/
public static function getLayoutContentParam(): string
{
return self::$LAYOUT_CONTENT ;
return self::$layout_content_param ;
}

/**
* @return string
*/
public static function getViewFolder()
{
return self::$VIEW_FOLDER ;
Expand All @@ -154,9 +153,69 @@ public function router(): Router

/**
* @return void
* @throws \Exception
*/
protected function routeProvider(): void
{
$base_route_path = self::getRootDir() . '/routes';
$api_route_path = $base_route_path . '/api.php';
if (file_exists($api_route_path)) {
$this->router->group([
'pattern' => '/api'
], function (Router $router) {
if (isset($_SERVER['HTTP_ORIGIN'])) {
// Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
// you want to allow, and if so:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
header('Access-Control-Allow-Methods: GET, POST,PUT, PATCH, HEAD, OPTIONS');
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
// may also be using PUT, PATCH, HEAD etc.
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

exit(0);
}
$router->group([], $this->registerRoute('/api.php'));
});
}
$web_route_path = $base_route_path . '/web.php';
if (file_exists($web_route_path)) {
$this->router->group([], $this->registerRoute('/web.php'));
}
if (!file_exists($web_route_path) && !file_exists($api_route_path)) {
throw new \Exception('No Route file not found.');
}
}

/**
* route path
* @param string $path
* @return string
*/
public function registerRoute(string $path): string
{
return $this->basePath('/routes' . '/' . trim($path,'/'));
}
/**
* @param string $path
* @return string
*/
public function basePath(string $path): string
{
return self::$root_dir . '/' . trim($path,'/');
}

/**
* @return void
* @throws \Exception
*/
public function run()
public function run(): void
{
$this->routeProvider();
$this->router->run();
}
}
4 changes: 2 additions & 2 deletions src/Core/Bundles.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ class Bundles
private static array $header_link = [];

/**
* manage to add a javascript script on the page
* manage to add a JavaScript script on the page
* @param string $file
*/
static function insertCSS(string $file)
{
if (is_file(Application::$ROOT_DIR . '/assets/css/' . $file . '.css')) {
if (is_file(Application::getRootDir() . '/assets/css/' . $file . '.css')) {
$href = WEB_ROOT . "assets/css/$file.css";
$link = <<<EOF
<link rel="stylesheet" type="text/css" href="$href"/>
Expand Down
14 changes: 14 additions & 0 deletions src/Core/Routing/Providers/Contracts/RouteContract.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php
/*
* Copyright (c) 2024. Wepesi Dev Framework
*/

namespace Wepesi\Core\Routing\Providers\Contracts;

/**
* @template T
*/
interface RouteContract
{
public function call();
}
Loading

0 comments on commit 82e31b1

Please sign in to comment.