Newer
Older
flow-task / server / Kernel / Classes / Router.php
@root root 20 days ago 1 KB ---
<?php

namespace Kernel\Classes;

class Router {
	protected $routes = ["GET" => [], "POST" => []];
	protected $err_404_handler;

	public function __construct() {
		$this -> err_404_handler = function(){ 
			return "404";
		};
	}

	public function routing() :String {
		if(!isset($_GET["action"]) and !isset($_POST["action"])) {
			return response_prepared($this -> err_404_handler());
		}

		$actions = [$_GET["action"] ?? "", $_POST["action"] ?? ""];

		$results = [];
		foreach(["GET", "POST"] as $i => $method) {
			if(isset($this -> routes[$method][$actions[$i]])) {
				$results = array_merge($results, $this -> call_action_handlers($this -> routes[$method][$actions[$i]]));
			}
		}

		return response_prepared($results);
	}

	public function linking(String $method, String $action_name, $action) :bool {
		if(!in_array($method, ["GET", "POST"])) {
			return throw new Exception("Method `{$method}` no exists");
		}

		if(!isset($this -> routes[$method][$action_name])) {
			$this -> routes[$method][$action_name] = [];
		}

		$this -> routes[$method][$action_name][] = $action;

		return true;
	} 

	public function set_err_404($handler) {
		return $this -> err_404_handler = $handler;
	}

	public function call_action_handlers(Array $handlers) :Array {
		$results = [];

		foreach($handlers as $handler) {
			$results[] = $handler();
		}

		return $results;
	}
}