MilkCore

Route
in package

Page Routing and URL Management Class

This class manages page routing within the system, allowing you to register and execute specific functions for pages, build URLs, and handle redirects. It provides a simple routing mechanism for the framework.

See the documentation for the AbstractRoute class for advanced usage.

Tags
see
AbstractRoute
example
// Register a route
Route::set('home', function() {
    echo 'Welcome to the homepage!';
});

// Register a route with permission check
Route::set('admin', function() {
    echo 'Admin panel';
}, 'auth.manage');

// Execute a route
Route::run('home');

// Generate a URL
$url = Route::url(['page' => 'products', 'id' => 123]);
// Result: https://example.com/?page=products&id=123

Table of Contents

Methods

compare_page_url()  : bool
Compares if the page parameter between query1 and query2 are equal
compare_query_url()  : bool
Compares if parameters of query1 are included in query2
current_url()  : string
Returns the current URL including query parameters
extract_credentials()  : array<string|int, mixed>
Extracts username and password from HTTP request
get_bearer_token()  : string|false
Retrieves a bearer token from the Authorization header
get_header_data()  : array<string|int, mixed>
Retrieves data from headers
get_query_string()  : string
Gets the current query string
get_route_permission()  : string|null
Gets the permission required for a specific route
get_routes_with_permissions()  : array<string|int, mixed>
Gets all routes with their permission requirements
get_session_data()  : array<string|int, mixed>
Retrieves session data passed through redirects
has_permission_requirement()  : bool
Checks if a route has a permission requirement
parse_query_string()  : array<string|int, mixed>
Parses the query string and returns an associative array
redirect()  : void
Performs a redirect with data in headers
redirect_error()  : void
Performs a redirect with an error message
redirect_handler_errors()  : void
Performs a redirect with handler errors
redirect_success()  : void
Performs a redirect with a success message
run()  : bool
Executes the function registered for a specific route
set()  : void
Registers a function to be called when a page is requested
url()  : string
Returns the site URL with optional query parameters
urlsafeB64Decode()  : string
Decodes a URL-safe Base64 string
urlsafeB64Encode()  : string
Encodes a string in URL-safe Base64 format

Methods

compare_page_url()

Compares if the page parameter between query1 and query2 are equal

public static compare_page_url(string|array<string|int, mixed> $query1[, string|array<string|int, mixed> $query2 = [] ]) : bool

To check if the sidebar menu is active, it's sufficient to use this method. This method only compares the 'page' parameter of the queries.

Parameters
$query1 : string|array<string|int, mixed>

First query to compare

$query2 : string|array<string|int, mixed> = []

Second query to compare (default: current query)

Tags
example
$isActive = Route::compare_page_url(['page' => 'home']);
// or
$isActive = Route::compare_page_url('?page=home&action=foo');
Return values
bool

True if both queries have the same 'page' parameter

compare_query_url()

Compares if parameters of query1 are included in query2

public static compare_query_url(string|array<string|int, mixed> $query1[, string|array<string|int, mixed> $query2 = [] ]) : bool

This method verifies that all parameters from query1 exist in query2 with the same values. Useful for checking if a URL matches certain criteria.

Parameters
$query1 : string|array<string|int, mixed>

First query to compare

$query2 : string|array<string|int, mixed> = []

Second query to compare (default: current query)

Tags
example
$selected = (Route::compare_query_url('page=home') ? 'selected' : '');
Return values
bool

True if query1 parameters are all present in query2

current_url()

Returns the current URL including query parameters

public static current_url() : string

This method generates the complete URL for the current page, including any query parameters that were passed in the request.

Tags
example
// Get the current URL
$currentUrl = Route::current_url();
// If the current page is https://example.com/?page=products&id=123
// Result: https://example.com/?page=products&id=123
Return values
string

The current URL with query parameters

extract_credentials()

Extracts username and password from HTTP request

public static extract_credentials([string $username_key = 'username' ][, string $password_key = 'password' ]) : array<string|int, mixed>

This method handles different authentication methods: Basic Auth, POST, and JSON body. It attempts to extract credentials from various sources in order of preference:

  1. HTTP Basic Authentication
  2. Authorization header with Basic auth
  3. POST parameters
  4. JSON request body
Parameters
$username_key : string = 'username'

Optional custom key for username field (default: 'username')

$password_key : string = 'password'

Optional custom key for password field (default: 'password')

Tags
example
$credentials = Route::extract_credentials();
print_r($credentials);

// With custom keys
$credentials = Route::extract_credentials('user', 'pass');
print_r($credentials);
Return values
array<string|int, mixed>

Associative array with 'username' and 'password', or empty values if not found

get_bearer_token()

Retrieves a bearer token from the Authorization header

public static get_bearer_token() : string|false

This method searches for a Bearer token in various authorization headers and returns it if found. It checks multiple possible header locations for maximum compatibility.

Tags
example
$token = Route::get_bearer_token();
if ($token !== false) {
    echo "Bearer token found: " . $token;
} else {
    echo "No Bearer token found";
}
Return values
string|false

Bearer token or false if not found

get_header_data()

Retrieves data from headers

public static get_header_data() : array<string|int, mixed>

This method is used to define different groups of sessions. The idea is that every time a redirect is made, a session identifier is passed on which the data to be passed has been saved.

It looks for cookies with the prefix 'X-Redirect-' and decodes their values, then cleans up the cookies after reading them.

Return values
array<string|int, mixed>

Retrieved data from headers/cookies

get_query_string()

Gets the current query string

public static get_query_string() : string

This method returns the current page's query string, ensuring it starts with '?'.

Return values
string

The current query string starting with '?'

get_route_permission()

Gets the permission required for a specific route

public static get_route_permission(string $name) : string|null
Parameters
$name : string

The route name

Return values
string|null

The required permission or null if no permission is set

get_routes_with_permissions()

Gets all routes with their permission requirements

public static get_routes_with_permissions() : array<string|int, mixed>
Return values
array<string|int, mixed>

Array of routes with their permissions

get_session_data()

Retrieves session data passed through redirects

public static get_session_data() : array<string|int, mixed>

This method retrieves data that was passed during a redirect using the session mechanism. It automatically cleans up the session data after retrieval.

Return values
array<string|int, mixed>

The session data or empty array if no data found

has_permission_requirement()

Checks if a route has a permission requirement

public static has_permission_requirement(string $name) : bool
Parameters
$name : string

The route name

Return values
bool

True if the route has a permission requirement, false otherwise

parse_query_string()

Parses the query string and returns an associative array

public static parse_query_string(string $query_string) : array<string|int, mixed>

This method converts a query string like "page=home&lang=it" into an associative array ['page' => 'home', 'lang' => 'it'].

Parameters
$query_string : string

The query string to parse

Tags
example
$query = Route::parse_query_string('page=home&lang=it');
print_r($query);
// Output: ['page' => 'home', 'lang' => 'it']
Return values
array<string|int, mixed>

Associative array of query parameters

redirect()

Performs a redirect with data in headers

public static redirect(string|array<string|int, mixed> $url[, array<string|int, mixed> $data = [] ]) : void

This method handles redirects to other pages and can pass data through session storage. If data is provided, it saves the data in session and passes a session ID through cookies for retrieval on the destination page.

Parameters
$url : string|array<string|int, mixed>

Destination URL or query parameters array

$data : array<string|int, mixed> = []

Data to pass in the header/session

Tags
example
// Simple redirect
Route::redirect(['page' => 'home']);

// Redirect with data
Route::redirect(['page' => 'home'], ['user_id' => 123, 'message' => 'Hello']);

redirect_error()

Performs a redirect with an error message

public static redirect_error(string|array<string|int, mixed> $url[, string $message = '' ][, array<string|int, mixed> $data = [] ]) : void

This method executes a redirect to the specified URL and passes an error message that can be displayed on the destination page.

Parameters
$url : string|array<string|int, mixed>

URL of destination or query parameters array

$message : string = ''

Error message to display

$data : array<string|int, mixed> = []

Additional data to pass with the redirect

redirect_handler_errors()

Performs a redirect with handler errors

public static redirect_handler_errors(string|array<string|int, mixed> $url[, array<string|int, mixed> $data = [] ]) : void

This method executes a redirect and passes any errors from the MessagesHandler.

Parameters
$url : string|array<string|int, mixed>

URL of destination or query parameters array

$data : array<string|int, mixed> = []

Additional data to pass with the redirect

redirect_success()

Performs a redirect with a success message

public static redirect_success(string|array<string|int, mixed> $url[, string $message = '' ][, array<string|int, mixed> $data = [] ]) : void

This method executes a redirect to the specified URL and passes a success message that can be displayed on the destination page.

Parameters
$url : string|array<string|int, mixed>

URL of destination or query parameters array

$message : string = ''

Success message to display

$data : array<string|int, mixed> = []

Additional data to pass with the redirect

run()

Executes the function registered for a specific route

public static run(string $name) : bool

This method runs the callback function associated with the specified route name. It also triggers 'route_before_run' and 'route_after_run' hooks, allowing for pre and post-processing of routes.

If a permission is associated with the route, it checks if the current user has the required permission. If not, it redirects to the 'deny' route.

Parameters
$name : string

The route name to execute (managed in index.php)

Tags
example
// Run the 'home' route
if (Route::run('home')) {
    // Route was found and executed
} else {
    // Route not found, handle 404
    echo 'Page not found';
}
Return values
bool

True if the route was found and executed, false otherwise

set()

Registers a function to be called when a page is requested

public static set(string $name, callable $function[, string|null $permission = null ]) : void

This method allows you to register a callback function that will be executed when the specified route is run. It's the foundation of the routing system.

Parameters
$name : string

The route name/identifier

$function : callable

The function to execute when this route is run

$permission : string|null = null

The permission required to access this route (format: 'group.permission_name')

Tags
example
// Register a simple route
Route::set('home', function() {
    echo 'Welcome to the homepage!';
});

// Register a route with permission check
Route::set('admin', function() {
    echo 'Admin panel';
}, 'auth.manage');

// Register a route with a controller method and permission
Route::set('products', [ProductController::class, 'index'], 'products.view');

url()

Returns the site URL with optional query parameters

public static url([mixed $query = '' ]) : string

This method generates a complete URL for the site, optionally including query parameters. It can accept parameters as an array or as a query string.

Parameters
$query : mixed = ''

Query parameters as array or string (default: '')

Tags
example
// Basic URL
$baseUrl = Route::url();
// Result: https://example.com/

// URL with query parameters as array
$url = Route::url(['page' => 'products', 'category' => 'electronics']);
// Result: https://example.com/?page=products&category=electronics

// URL with query string
$url = Route::url('?page=contact');
// Result: https://example.com/?page=contact
Return values
string

The complete URL

urlsafeB64Decode()

Decodes a URL-safe Base64 string

public static urlsafeB64Decode(string $input) : string

This method decodes a URL-safe Base64 encoded string back to its original form.

Parameters
$input : string

The URL-safe Base64 string to decode

Return values
string

The decoded string

urlsafeB64Encode()

Encodes a string in URL-safe Base64 format

public static urlsafeB64Encode(string $input) : string

This method encodes a string in Base64 and makes it URL-safe by replacing characters that have special meaning in URLs.

Parameters
$input : string

The string to encode

Return values
string

The URL-safe Base64 encoded string


        
On this page

Search results