File: //usr/local/mailchannels/lib/PathRegistry.php
<?php
namespace MailChannels;
require_once("PathEntry.php");
/*
* PathRegistry allows the user to assign a combination of a url path, action, and method to certain "controller" and
* function. PathEntries are assigned to controllers via the registerPath function. Calling resolvePath with an assigned
* PathEntry results in the assign function being called on the assigned controller.
*/
final class PathRegistry {
private static $entries = array();
/*
* registerPath assigns a controller and function to the given path, action, and method.
*/
public static function registerPath($path, $action, $method, $controller, $function="index") {
classExtends($controller, BaseController::class);
if (self::entryExists($path, $action, $method)) {
return false;
}
self::$entries[$path][$action][$method] = new PathEntry($controller, $function);
return true;
}
/*
* resolvePath looks for the corresponding controller and function to match the requests path, action, and method,
* then calls the given function on that controller. The controller and function must have been registered to the path,
* action, and method using the registerPath function.
*/
public static function resolvePath($path, $action, $method) {
$config = App::getConfig();
if (!$config::CORS_ENABLED && $method === "OPTIONS") {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: *');
return;
}
if (!$action) {
$action = "index";
}
if (!self::entryExists($path, $action, $method)) {
App::showPageNotFound();
} else {
$pathEntry = self::$entries[$path][$action][$method];
$controllerName = $pathEntry->getController();
$functionName = $pathEntry->getFunction();
if (!class_exists($controllerName)) {
App::showInternalError();
}
$controller = new $controllerName();
if (!method_exists($controller, $functionName)) {
App::showInternalError();
}
$controller->$functionName();
}
}
/*
* entryExists checks if there is an entry in the "entries" variable corresponding to the variables passed to this function.
*/
private static function entryExists() {
$args = func_get_args();
$arr = self::$entries;
foreach ($args as $arg) {
if (!array_key_exists($arg, $arr)) {
return false;
}
$arr = $arr[$arg];
}
return true;
}
}