From 02e9a3df2358c61bc52e61659ca183161a9c1b99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=B5=9C=EC=A4=80=ED=9D=A0?= Date: Mon, 7 Apr 2025 17:22:59 +0900 Subject: [PATCH] dbms_primeidc_init...1 --- extdbms/composer.json | 11 +- extdbms/index.php | 14 +- extdbms/lib/Configs/App.php | 23 +-- extdbms/lib/Configs/Route.php | 83 +++++++++ .../DBMS/Client/DashboardController.php | 12 +- .../DBMS/Client/MemoController.php | 38 +++-- .../Controllers/DBMS/DashboardController.php | 21 ++- .../Controllers/DBMS/NavigatorController.php | 6 +- .../Controllers/DBMS/ServiceController.php | 14 +- extdbms/lib/Controllers/HomeController.php | 17 +- extdbms/lib/Core/App.php | 161 +++--------------- extdbms/lib/Core/Controller.php | 42 +---- extdbms/lib/Core/Helper.php | 37 ++++ extdbms/lib/Core/MiddlewareInterface.php | 8 + extdbms/lib/Core/Response.php | 27 +++ extdbms/lib/Core/Router.php | 133 +++++++++++++++ extdbms/lib/Middlewares/AuthMiddleware.php | 19 +++ .../memo/{insert_formphp => update_form.php} | 6 +- .../Views/dbms/dashboard/latest_service.php | 2 +- extdbms/lib/Views/dbms/navigator/ipsearch.php | 4 +- 20 files changed, 416 insertions(+), 262 deletions(-) create mode 100644 extdbms/lib/Configs/Route.php create mode 100644 extdbms/lib/Core/MiddlewareInterface.php create mode 100644 extdbms/lib/Core/Response.php create mode 100644 extdbms/lib/Core/Router.php create mode 100644 extdbms/lib/Middlewares/AuthMiddleware.php rename extdbms/lib/Views/dbms/client/memo/{insert_formphp => update_form.php} (68%) diff --git a/extdbms/composer.json b/extdbms/composer.json index 6658e43..fd34d62 100644 --- a/extdbms/composer.json +++ b/extdbms/composer.json @@ -1,10 +1,13 @@ { + "name": "my dbms", + "description": "DBMS framework", + "type": "project", "require": { - "vlucas/phpdotenv": "^5.6" + "php": ">=8.2" }, "autoload": { "psr-4": { - "lib\\Controllers\\": "lib/Controllers/" + "lib\\": "lib/" } - } -} + } +} \ No newline at end of file diff --git a/extdbms/index.php b/extdbms/index.php index 781ac05..14973df 100644 --- a/extdbms/index.php +++ b/extdbms/index.php @@ -1,22 +1,14 @@ load(); - // 테스트 URL : "http://test.com/Control/Method/arg1/arg2"; - // 요청된 URL 경로 가져오기 - $url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : false; - if (!$url) { - $url = isset($argv[1]) ? $argv[1] : false; - } - $app = new App($url); - return $app->run(); + $app = new App(); + $app->run(); } catch (\Exception $e) { echo $e->getMessage(); } diff --git a/extdbms/lib/Configs/App.php b/extdbms/lib/Configs/App.php index 0911b53..26c30a2 100644 --- a/extdbms/lib/Configs/App.php +++ b/extdbms/lib/Configs/App.php @@ -2,25 +2,16 @@ namespace lib\Configs; -use lib\Core\App as Core; +use \lib\Core\App as Core; +use Dotenv\Dotenv; class App extends Core { - public function __construct(string $url) + public function __construct() { - parent::__construct($url); - } - - protected function routeMethod(string $route): string - { - switch ($route) { - case 'service': - $route = 'latest_service'; - break; - case 'history': - $route = 'latest_history'; - break; - } - return parent::routeMethod($route); + // .env 파일 로드 + $dotenv = Dotenv::createImmutable(ROOT_PATH); + $dotenv->load(); + parent::__construct(); } } diff --git a/extdbms/lib/Configs/Route.php b/extdbms/lib/Configs/Route.php new file mode 100644 index 0000000..1605bf5 --- /dev/null +++ b/extdbms/lib/Configs/Route.php @@ -0,0 +1,83 @@ +group('dbms/dashboard', function (Router $router) { + // 동적 파라미터 없이 기본 path에 추가 파라미터를 받아 key/value 형식으로 처리 + $router->add('GET', '', function ($params) { + Response::json([ + 'message' => 'DashboardController::index 실행됨', + 'params' => $params + ]); + }); + // 동적 파라미터 없이 기본 path에 추가 파라미터를 받아 key/value 형식으로 처리 + $router->add('GET', 'topboard', function ($params) { + $controller = new DashboardController($params); + return $controller->topboard(); + // Response::view($result); + }); + $router->add('GET', 'totalcount', function ($params) { + $controller = new DashboardController(); + return $controller->totalcount($params); + // Response::view($result); + }); + $router->add('GET', 'latest_service', function ($params) { + $controller = new DashboardController(); + return $controller->latest_service($params); + // Response::view($result); + }); + $router->add('GET', 'latest_history', function ($params) { + $controller = new DashboardController(); + return $controller->latest_history($params); + // Response::view($result); + }); +}); + +$router->group('dbms/navigator', function (Router $router) { + // 동적 파라미터 없이 기본 path에 추가 파라미터를 받아 key/value 형식으로 처리 + $router->add('GET', 'ipsearch', function ($params) { + $controller = new NavigatorController(); + return $controller->ipsearch($params); + // Response::view($result); + }); +}); + +$router->group('dbms/service', function (Router $router) { + // 동적 파라미터 없이 기본 path에 추가 파라미터를 받아 key/value 형식으로 처리 + $router->add('GET', 'extra', function ($params) { + $controller = new ServiceController(); + return $controller->extra($params); + // Response::view($result); + }); +}); + +$router->group('dbms/client/dashboard', function (Router $router) { + // 동적 파라미터 없이 기본 path에 추가 파라미터를 받아 key/value 형식으로 처리 + $router->add('GET', 'totalcount', function ($params) { + $controller = new \lib\Controllers\DBMS\Client\DashboardController(); + return $controller->totalcount($params); + // Response::view($result); + }); +}); + +$router->group('dbms/client/memo', function (Router $router) { + $router->add('GET', 'update_form', function ($params) { + $controller = new MemoController(); + return $controller->update_form($params); + // Response::view($result); + }); + $router->add('POST', 'update', function ($params) { + $controller = new MemoController(); + return $controller->update($params); + // Response::view($result); + }); +}); diff --git a/extdbms/lib/Controllers/DBMS/Client/DashboardController.php b/extdbms/lib/Controllers/DBMS/Client/DashboardController.php index fa995f0..4b6f2c9 100644 --- a/extdbms/lib/Controllers/DBMS/Client/DashboardController.php +++ b/extdbms/lib/Controllers/DBMS/Client/DashboardController.php @@ -15,15 +15,12 @@ class DashboardController extends ClientController //서비스카운팅 , total_counting_customer.php //CLI 접속방법 : php index.php site/client/dashboard/totalcount/client_code/코드번호 //WEB 접속방법 : http://localhost/site/client/dashboard/totalcount/client_code/코드번호 - public function totalcount(mixed $client_code = null) + public function totalcount(array $params) { - if ($client_code === null) { - $client_code = $this->getSegments('client_code'); - if ($client_code === null) { - throw new \Exception("client_code 값이 정의되지 않았습니다."); - } + if (!array_key_exists('client_code', $params)) { + throw new \Exception("client_code 값이 정의되지 않았습니다."); } - $this->client_code = $client_code; + $client_code = $params['client_code']; $dashboard = []; foreach (DBMS_SERVICE_SWITCHCODE as $district => $switchcodes) { $switchcode_begin = $switchcodes['begin']; @@ -39,6 +36,7 @@ class DashboardController extends ClientController } //foreach $dashboard['coupon'] = $this->getServiceService()->getCouponCountByClient($client_code); $this->dashboard = $dashboard; + $this->client_code = $client_code; return $this->render(__FUNCTION__); } } //Class diff --git a/extdbms/lib/Controllers/DBMS/Client/MemoController.php b/extdbms/lib/Controllers/DBMS/Client/MemoController.php index acced51..e683b73 100644 --- a/extdbms/lib/Controllers/DBMS/Client/MemoController.php +++ b/extdbms/lib/Controllers/DBMS/Client/MemoController.php @@ -2,7 +2,7 @@ namespace lib\Controllers\DBMS\Client; -use lib\Services\ClientService; +use lib\Helpers\ServiceHelper; class MemoController extends ClientController { @@ -10,19 +10,37 @@ class MemoController extends ClientController { parent::__construct(); $this->getView()->setPath('memo'); + $this->helper = new ServiceHelper(); } // //사용자용메모장 , customer_memo.php - //CLI 접속방법 : php index.php site/client/memo/insert_form/client_code/코드번호 - //WEB 접속방법 : http://localhost/site/client/memo/insert_form/client_code/코드번호 - public function insert_form(mixed $client_code = null) + //CLI 접속방법 : php index.php site/client/memo/update_form/client_code/코드번호 + //WEB 접속방법 : http://localhost/site/client/memo/update_form/client_code/코드번호 + public function update_form(array $params) { - if ($client_code === null) { - $client_code = $this->getSegments('client_code'); - if ($client_code === null) { - throw new \Exception("client_code 값이 정의되지 않았습니다."); - } + if (!array_key_exists('client_code', $params)) { + throw new \Exception("client_code 값이 정의되지 않았습니다."); + } + $client_code = $params['client_code']; + $this->getClientService()->getModel()->where("Client_Code", $client_code); + $entity = $this->getClientService()->getEntity(); + if (!$entity) { + throw new \Exception("[$client_code]에 해당하는 사용자정보가 존재하지 않습니다."); + } + $this->entity = $entity; + return $this->render(__FUNCTION__); + } + + public function update(array $params) + { + if (!array_key_exists('client_code', $params)) { + throw new \Exception("client_code 값이 정의되지 않았습니다."); + } + $client_code = $params['client_code']; + $this->getClientService()->getModel()->where("Client_Code", $client_code); + $entity = $this->getClientService()->getEntity(); + if (!$entity) { + throw new \Exception("[$client_code]에 해당하는 사용자정보가 존재하지 않습니다."); } - $this->entity = $this->getClientService()->getModel()->where("Client_Code", $client_code); return $this->render(__FUNCTION__); } } //Class diff --git a/extdbms/lib/Controllers/DBMS/DashboardController.php b/extdbms/lib/Controllers/DBMS/DashboardController.php index 8e5c837..526e5b7 100644 --- a/extdbms/lib/Controllers/DBMS/DashboardController.php +++ b/extdbms/lib/Controllers/DBMS/DashboardController.php @@ -80,15 +80,16 @@ class DashboardController extends DBMSController //서비스카운팅 , total_counting.php //CLI 접속방법 : php index.php site/dashboard/totalcount/sitekey/도메인 //WEB 접속방법 : http://localhost/site/dashboard/totalcount/sitekey/도메인 - public function totalcount(mixed $sitekey = null) + public function totalcount(array $params) { - if ($sitekey === null) { - $sitekey = $this->getSegments('sitekey'); - if ($sitekey === null) { - throw new \Exception("sitekey 값이 정의되지 않았습니다."); - } + if (!array_key_exists('sitekey', $params)) { + throw new \Exception("sitekey 값이 정의되지 않았습니다."); } + $sitekey = $params['sitekey']; //사이트 정보 가져오기 + if (!array_key_exists($sitekey, DBMS_SITEINFOS)) { + throw new \Exception("[{$sitekey}]에 해당하는 사이트정보가 없습니다."); + } $this->siteInfo = DBMS_SITEINFOS[$sitekey]; $this->totalcount = $this->getServiceService()->getTotalCountForDashboard($this->siteInfo); $summary = array(); @@ -116,14 +117,15 @@ class DashboardController extends DBMSController //신규서버현황 new_server_list.php //CLI 접속방법 : php index.php site/dashboard/latest_service/limit/5 //WEB 접속방법 : http://localhost/site/dashboard/latest_service/limit/5 - public function latest_service(mixed $limit = 5) + public function latest_service(array $params) { + $limit = array_key_exists('limit', $params) ? $params['limit'] : 5; //신규서버정보 $this->limit = intval($limit); $this->entities = $this->getServiceService()->getLatest($this->limit); // echo $this->getServiceervice()->getModel()->getLastQuery(); //전체 관리자정보(등록자) - $this->users = $this->getMemberService()->getEntities(); + $this->members = $this->getMemberService()->getEntities(); $clients = []; $vpcs = []; $kcss = []; @@ -150,8 +152,9 @@ class DashboardController extends DBMSController } //CLI 접속방법 : php index.php site/dashboard/latest_history/limit/5 //WEB 접속방법 : http://localhost/site/dashboard/latest_history/limit/5 - public function latest_history(mixed $limit = 5): string + public function latest_history(array $params): string { + $limit = array_key_exists('limit', $params) ? $params['limit'] : 5; //신규서버정보 $this->limit = intval($limit); $this->entitys = $this->getHistoryService()->getLatest($this->limit); diff --git a/extdbms/lib/Controllers/DBMS/NavigatorController.php b/extdbms/lib/Controllers/DBMS/NavigatorController.php index 15c03f1..de622ac 100644 --- a/extdbms/lib/Controllers/DBMS/NavigatorController.php +++ b/extdbms/lib/Controllers/DBMS/NavigatorController.php @@ -26,11 +26,11 @@ class NavigatorController extends DBMSController //부가서비스 : 닷디펜더,딥파인더 등, deepfinder_list.php,dotdefender_list.php //CLI 접속방법 : php index.php site/navigator/ipsearch //WEB 접속방법 : http://localhost/site/navigator/ipsearch - public function ipsearch(): string + public function ipsearch(array $params): string { + $ip = array_key_exists('ip', $params) ? $params['ip'] : null; //전체 고객정보 $this->clients = $this->getClientService()->getEntities(); - $ip = $this->getRequest('ip') ?? ''; //IP형식이 ipv4인지 확인 후 값가져오기 $services = []; if ($ip && $this->helper->isIPAddress($ip)) { @@ -42,7 +42,7 @@ class NavigatorController extends DBMSController } else { $services = $this->getServiceService()->getEntities(); } - $this->request = $this->getRequest(); + $this->ip = $ip; $this->services = $services; return $this->render(__FUNCTION__); } diff --git a/extdbms/lib/Controllers/DBMS/ServiceController.php b/extdbms/lib/Controllers/DBMS/ServiceController.php index 9b50238..f9ba244 100644 --- a/extdbms/lib/Controllers/DBMS/ServiceController.php +++ b/extdbms/lib/Controllers/DBMS/ServiceController.php @@ -31,21 +31,19 @@ class ServiceController extends DBMSController return $this->_addDbService; } - //부가서비스 : 닷디펜더,딥파인더 등, deepfinder_list.php,dotdefender_list.php + //부가서비스 : 닷 디펜더,딥 파인더 ,M307-1,M394-2등, deepfinder_list.php,dotdefender_list.php //CLI 접속방법 : php index.php site/service//extra/adddb_code/코드번호 //WEB 접속방법 : http://localhost/site/service/extra/adddb_code/코드번호 - public function extra(mixed $adddb_code = null): string + public function extra(array $params): string { - if ($adddb_code === null) { - $adddb_code = $this->getSegments('adddb_code'); - if ($adddb_code === null) { - throw new \Exception("adddb_code 값이 정의되지 않았습니다."); - } + if (!array_key_exists('adddb_code', $params)) { + throw new \Exception("adddb_code 값이 정의되지 않았습니다."); } + $adddb_code = urldecode($params['adddb_code']); //해당 부가서비스의 services_code 목록 가져오기 //segment의 값이 한글인경우 urldecode가 필요 $service_codes = []; - $this->getAddDbService()->getModel()->where('addDB_code', urldecode($adddb_code)); + $this->getAddDbService()->getModel()->where('addDB_code', $adddb_code); $entitys = $this->getAddDbService()->getEntities(); foreach ($entitys as $entity) { $service_codes[] = $entity->getServiceCode(); diff --git a/extdbms/lib/Controllers/HomeController.php b/extdbms/lib/Controllers/HomeController.php index d0c40ec..59c6d63 100644 --- a/extdbms/lib/Controllers/HomeController.php +++ b/extdbms/lib/Controllers/HomeController.php @@ -2,14 +2,15 @@ namespace lib\Controllers; -class HomeController extends CommonController +use lib\Core\Response; + +class HomeController { - public function __construct() + public function index(array $params = []): void { - parent::__construct(); - } // - public function index() - { - echo __FUNCTION__ . "실행완료"; + Response::json([ + 'message' => 'Welcome to the home page!', + 'params' => $params + ]); } -} //Class +} diff --git a/extdbms/lib/Core/App.php b/extdbms/lib/Core/App.php index a5b2fbd..a362f1a 100644 --- a/extdbms/lib/Core/App.php +++ b/extdbms/lib/Core/App.php @@ -2,149 +2,32 @@ namespace lib\Core; -use lib\Core\Controller; +use lib\Core\Router; +use lib\Core\Response; abstract class App { - private string $_url = ""; - private string $_baseControllerPath = 'lib' . DIRECTORY_SEPARATOR . 'Controllers' . DIRECTORY_SEPARATOR; - private array $_controllerPaths = []; - protected ?Controller $_controller; - protected string $_method = ""; - protected array $_segments = []; + protected function __construct() + { + // 초기화 작업 + } + public function run(): void + { + $router = new Router(); + // 기본 홈 라우트 + $router->add('GET', '', function ($params) { + Response::text("홈 페이지"); + }); + require_once ROOT_PATH . '/lib/Configs/Route.php'; + // CLI 요청인지 웹 요청인지에 따라 URI 파싱 + $uri = php_sapi_name() === 'cli' ? $this->parseCliUri() : $_SERVER['REQUEST_URI']; + $method = php_sapi_name() === 'cli' ? 'GET' : $_SERVER['REQUEST_METHOD']; + $router->dispatch($uri, $method); + } - public function __construct(string $url) + private function parseCliUri(): string { - $this->_url = $url; - $this->init(); - } - final public function getURL(): string - { - return $this->_url; - } - private function init(): void - { - $path = parse_url($this->getURL(), PHP_URL_PATH); - $arguments = explode('/', trim($path, '/')); - // var_dump($arguments); - //컨트롤러와 메서드를 설정 - $this->setControllerPath($arguments); - $this->setController($arguments); - $this->setMethod($arguments); - // 남은 세그먼트를 파라미터로 설정 - $this->setSegments($arguments); - } - protected function routeModule(string $route): string - { - return $route; - } - protected function routeController(string $route): string - { - return ucfirst($route . 'Controller'); - } - protected function routeMethod(string $route): string - { - return $route; - } - private function getControllerPath(): string - { - return implode(DIRECTORY_SEPARATOR, $this->_controllerPaths); - } - private function setControllerPath(array &$segments): void - { - $route = count($segments) ? $segments[0] : ''; - $route = $this->routeModule($route); - $fullDirectoryPath = ROOT_PATH . DIRECTORY_SEPARATOR . $this->_baseControllerPath . $this->getControllerPath() . DIRECTORY_SEPARATOR . $route; - // echo "Full RoutePath:{$fullRoutePath}\n"; - if (is_dir($fullDirectoryPath)) { - array_shift($segments); - $this->_controllerPaths[] = $route; - $this->setControllerPath($segments); - } - } - final protected function getController(): Controller - { - return $this->_controller; - } - private function setController(array &$segments): void - { - // echo $this->getControllerPath() . "\n"; - // var_dump($segments); - // exit; - $route = count($segments) ? $segments[0] : 'Home'; - $controller = str_replace('/', '\\', $this->_baseControllerPath . $this->getControllerPath() . DIRECTORY_SEPARATOR . $this->routeController($route)); - if (class_exists($controller, true)) { - $this->_controller = new $controller(); - } else { - throw new \Exception("[{$controller}] 해당 Controller를 찾을수 없습니다."); - } - array_shift($segments); - } - final protected function getMethod(): string - { - return $this->_method; - } - final protected function setMethod(array &$segments): void - { - //$segments[0]인이유는 setController에서 $segments를 array_shift했기때문 - $route = count($segments) ? $segments[0] : 'index'; - // echo "METHOD:{$route}\n"; - $method = $this->routeMethod($route); - // echo get_class($this->getController()) . ",METHOD2:{$method}\n"; - if (method_exists($this->getController(), $method)) { - array_shift($segments); - } else { - throw new \Exception("해당 함수[{$method}]를 " . get_class($this->getController()) . "에서 찾을수 없습니다."); - } - $this->_method = $method; - } - final public function getSegments(): array - { - return $this->_segments; - } - final protected function setSegments(array &$segments): void - { - // 세그먼트 배열을 key/value 쌍으로 변환 - $params = []; - for ($i = 0; $i < count($segments); $i += 2) { - if (isset($segments[$i + 1])) { - $params[$segments[$i]] = $segments[$i + 1]; - } - } - $this->_segments = $params; - } - final public function run(): mixed - { - $controller = $this->getController(); - $method = $this->getMethod(); - // 컨트롤러에 세그먼트 전달 - $controller->setSegments($this->getSegments()); - // 키/값 형태로 세그먼트 처리 - $params = []; - $segments = $this->getSegments(); - // 메서드의 매개변수 정보 가져오기 - $reflectionMethod = new \ReflectionMethod($controller, $method); - $parameters = $reflectionMethod->getParameters(); - if (count($parameters) > 0) { - // 매개변수가 존재하면 URL 세그먼트를 순서대로 매개변수에 매핑 - foreach ($parameters as $i => $param) { - // 매개변수 이름을 가져와서 세그먼트에서 값을 찾기 - $paramName = $param->getName(); - if (isset($segments[$paramName])) { - $params[] = $segments[$paramName]; - } else if (isset($segments[$i])) { - $params[] = $segments[$i]; - } else if ($param->isDefaultValueAvailable()) { - $params[] = $param->getDefaultValue(); - } else { - $params[] = null; - } - } - } else { - // 매개변수가 없으면 빈 배열 전달 - $params = []; - } - - return call_user_func_array([$controller, $method], $params); + global $argv; + return $argv[1] ?? ''; } } diff --git a/extdbms/lib/Core/Controller.php b/extdbms/lib/Core/Controller.php index 005e493..eacc97e 100644 --- a/extdbms/lib/Core/Controller.php +++ b/extdbms/lib/Core/Controller.php @@ -8,13 +8,10 @@ use lib\Configs\View; abstract class Controller { - private $_module = ""; private $_request = null; private ?View $_view = null; - private $_segments = []; - protected function __construct(string $module = "") + protected function __construct() { - $this->_module = $module; $this->_view = new View(); } // final public function getView(): View @@ -29,43 +26,6 @@ abstract class Controller { $this->getView()->$name = $value; } - final public function getModule(): string - { - return $this->_module; - } - final public function setSegments(array $segments) - { - $this->_segments = $segments; - } - final public function getSegments(string $key = ""): mixed - { - if ($key === "") { - return $this->_segments; - } - return array_key_exists($key, $this->_segments) ? $this->_segments[$key] : null; - } - final public function getRequest(mixed $key = null, mixed $method = null): mixed - { - if ($this->_request === null) { - $this->_request = match (strtoupper($method)) { - "POST" => $_POST, - "GET" => $_GET, - default => $_REQUEST, - }; - } - if ($key === null) { - return $this->_request; - } - return array_key_exists($key, $this->_request) ? $this->_request[$key] : null; - } - final public function getPost(mixed $key = null): mixed - { - return $this->getRequest($key, "POST"); - } - final public function getGet(mixed $key = null): mixed - { - return $this->getRequest($key, "GET"); - } public function render(string $path) { return $this->getView()->render($path); diff --git a/extdbms/lib/Core/Helper.php b/extdbms/lib/Core/Helper.php index 83c4a4e..d89a5af 100644 --- a/extdbms/lib/Core/Helper.php +++ b/extdbms/lib/Core/Helper.php @@ -5,4 +5,41 @@ namespace lib\Core; abstract class Helper { protected function __construct() {} // + + public static function baseUrl(): string + { + $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://"; + $host = $_SERVER['HTTP_HOST'] ?? 'localhost'; + $script = str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']); + + return rtrim($protocol . $host . $script, '/'); + } + + public static function currentUrl(): string + { + $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://"; + $host = $_SERVER['HTTP_HOST'] ?? 'localhost'; + $uri = $_SERVER['REQUEST_URI'] ?? ''; + + return $protocol . $host . $uri; + } + + public static function previousUrl(): ?string + { + return $_SERVER['HTTP_REFERER'] ?? null; + } + + public static function urlIs(string $pattern): bool + { + $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); + $pattern = str_replace('*', '.*', preg_quote($pattern, '/')); + return preg_match("/^{$pattern}$/", $uri) === 1; + } + + public static function getSegment(int $index): ?string + { + $uri = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/'); + $segments = explode('/', $uri); + return $segments[$index - 1] ?? null; + } } //Class diff --git a/extdbms/lib/Core/MiddlewareInterface.php b/extdbms/lib/Core/MiddlewareInterface.php new file mode 100644 index 0000000..9e3e217 --- /dev/null +++ b/extdbms/lib/Core/MiddlewareInterface.php @@ -0,0 +1,8 @@ +currentGroupPrefix . '/' . trim($path, '/'), '/'); + + $route = [ + 'method' => strtoupper($method), + 'path' => $fullPath, + 'callback' => $callback, + 'middlewares' => array_merge($this->currentGroupMiddlewares, $middlewares) + ]; + + // 동적 파라미터({param})가 있으면 정규식 패턴 생성 + if (strpos($fullPath, '{') !== false) { + $pattern = preg_replace_callback('/\{(\w+)\}/', function ($matches) { + return '(?P<' . $matches[1] . '>[^/]+)'; + }, $fullPath); + $route['pattern'] = '/^' . str_replace('/', '\/', $pattern) . '(\/.*)?$/'; + } else { + // SEO key/value 형태를 위해 접두사 이후의 추가 파라미터를 허용 + $route['pattern'] = '/^' . str_replace('/', '\/', $fullPath) . '(\/(?P.*))?$/'; + } + + $this->routes[] = $route; + } + + /** + * 라우트 그룹: 공통 접두사와 공통 미들웨어를 적용 + */ + public function group(string $prefix, callable $callback, array $middlewares = []): void + { + $previousGroupPrefix = $this->currentGroupPrefix; + $previousGroupMiddlewares = $this->currentGroupMiddlewares; + + $this->currentGroupPrefix = trim($previousGroupPrefix . '/' . trim($prefix, '/'), '/'); + $this->currentGroupMiddlewares = array_merge($previousGroupMiddlewares, $middlewares); + + $callback($this); + + $this->currentGroupPrefix = $previousGroupPrefix; + $this->currentGroupMiddlewares = $previousGroupMiddlewares; + } + + /** + * 라우트 매칭 및 실행 + */ + public function dispatch(string $uri, string $method = 'GET'): void + { + $uri = trim(parse_url($uri, PHP_URL_PATH), '/'); + + // 정적 파일 처리: public 폴더 내에 파일이 있으면 직접 서빙 + $staticFile = __DIR__ . '/../../public/' . $uri; + if (file_exists($staticFile) && is_file($staticFile)) { + $this->serveStaticFile($staticFile); + return; + } + foreach ($this->routes as $route) { + if ($route['method'] !== strtoupper($method)) { + continue; + } + if (preg_match($route['pattern'], $uri, $matches)) { + $params = []; + + // 패턴에 named 그룹이 있다면 추출 + foreach ($matches as $key => $value) { + if (is_string($key)) { + $params[$key] = $value; + } + } + //추가 SEO key/value 파라미터로 파싱 + if (isset($params['extra']) && $params['extra'] !== '') { + $extra = trim($params['extra'], '/'); + $extraSegments = explode('/', $extra); + // 짝수개여야 key/value 쌍으로 변환 가능 + if (count($extraSegments) % 2 === 0) { + for ($i = 0; $i < count($extraSegments); $i += 2) { + $key = $extraSegments[$i]; + $value = $extraSegments[$i + 1]; + $params[$key] = $value; + } + } + unset($params['extra']); + } else { + // 패턴에 extra 그룹이 없으면, 기본 GET 파라미터와 병합 + $params = array_merge($_GET, $params); + } + $this->handle($route, $params); + return; + } + } + http_response_code(404); + echo "해당 Controller나 함수를 찾을수없습니다."; + } + + /** + * 미들웨어 체인을 거쳐 최종 콜백 실행 + */ + private function handle(array $route, array $params): void + { + $handler = $route['callback']; + $middlewares = $route['middlewares']; + + $pipeline = array_reduce( + array_reverse($middlewares), + fn($next, $middleware) => fn($params) => (new $middleware)->handle($params, $next), + $handler + ); + $pipeline($params); + } + + /** + * 정적 파일 서빙 (이미지, CSS, JS 등) + */ + private function serveStaticFile(string $file): void + { + $mimeType = mime_content_type($file); + header('Content-Type: ' . $mimeType); + readfile($file); + } +} diff --git a/extdbms/lib/Middlewares/AuthMiddleware.php b/extdbms/lib/Middlewares/AuthMiddleware.php new file mode 100644 index 0000000..2ba354f --- /dev/null +++ b/extdbms/lib/Middlewares/AuthMiddleware.php @@ -0,0 +1,19 @@ + 'Unauthorized'], 401); + return; + } + return $next($params); + } +} diff --git a/extdbms/lib/Views/dbms/client/memo/insert_formphp b/extdbms/lib/Views/dbms/client/memo/update_form.php similarity index 68% rename from extdbms/lib/Views/dbms/client/memo/insert_formphp rename to extdbms/lib/Views/dbms/client/memo/update_form.php index da98550..6768382 100644 --- a/extdbms/lib/Views/dbms/client/memo/insert_formphp +++ b/extdbms/lib/Views/dbms/client/memo/update_form.php @@ -1,11 +1,11 @@ -
- + + - + diff --git a/extdbms/lib/Views/dbms/dashboard/latest_service.php b/extdbms/lib/Views/dbms/dashboard/latest_service.php index d40e080..ecbd470 100644 --- a/extdbms/lib/Views/dbms/dashboard/latest_service.php +++ b/extdbms/lib/Views/dbms/dashboard/latest_service.php @@ -33,7 +33,7 @@ / kcss[$entity->getServiceCode()] ?> - + diff --git a/extdbms/lib/Views/dbms/navigator/ipsearch.php b/extdbms/lib/Views/dbms/navigator/ipsearch.php index 17346fb..fcd5866 100644 --- a/extdbms/lib/Views/dbms/navigator/ipsearch.php +++ b/extdbms/lib/Views/dbms/navigator/ipsearch.php @@ -81,10 +81,10 @@ box-shadow: inset -1px -1px 0 #fff; } -
+
[ 돌아가기 ] - IP 입력 : + IP 입력 :
비    고
users[$entity->getServiceCode()] ? "" : $this->users[$entity->getServiceCode()]->getTitle() ?>members[$entity->getMemberCode()] ? "" : $this->members[$entity->getMemberCode()]->getTitle() ?> helper->truncateString($entity->service_note, 20) ?>