| 1 |
<?php |
| 2 |
/** |
| 3 |
* Helper to enqueue ajax route, also generate the nonce's. |
| 4 |
* |
| 5 |
* @package Calotes\Helper |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace Calotes\Helper; |
| 9 |
|
| 10 |
/** |
| 11 |
* Helper to enqueue ajax route, also generate the nonce's. |
| 12 |
*/ |
| 13 |
class Route { |
| 14 |
|
| 15 |
/** |
| 16 |
* Array to store registered routes. |
| 17 |
* |
| 18 |
* @var array |
| 19 |
*/ |
| 20 |
protected static $routes = array(); |
| 21 |
|
| 22 |
/** |
| 23 |
* Array to store nonce's for registered routes. |
| 24 |
* |
| 25 |
* @var array |
| 26 |
*/ |
| 27 |
protected static $nonces = array(); |
| 28 |
|
| 29 |
/** |
| 30 |
* Registers a new route for handling AJAX requests. |
| 31 |
* |
| 32 |
* @param mixed $name The name of the route. |
| 33 |
* @param mixed $category The category of the route. |
| 34 |
* @param mixed $route The route to be registered. |
| 35 |
* @param mixed $callback The callback function to handle the request. |
| 36 |
* @param bool $nopriv Whether the route should be accessible without authentication. |
| 37 |
*/ |
| 38 |
public static function register_route( $name, $category, $route, $callback, $nopriv = false ) { |
| 39 |
$namespace = self::get_namespace( $category ); |
| 40 |
$route = $namespace . '/' . $route; |
| 41 |
add_action( 'wp_ajax_' . $route, $callback ); |
| 42 |
if ( true === $nopriv ) { |
| 43 |
add_action( 'wp_ajax_nopriv_' . $route, $callback ); |
| 44 |
} |
| 45 |
if ( ! isset( self::$routes[ $category ] ) ) { |
| 46 |
self::$routes[ $category ] = array(); |
| 47 |
self::$nonces[ $category ] = array(); |
| 48 |
} |
| 49 |
self::$routes[ $category ][ $name ] = $route; |
| 50 |
self::$nonces[ $category ][ $name ] = wp_create_nonce( $name . $category ); |
| 51 |
} |
| 52 |
|
| 53 |
/** |
| 54 |
* Retrieves the exported routes and nonce's for the specified categories. |
| 55 |
* |
| 56 |
* @param mixed $categories The categories for which to export routes and nonce's. |
| 57 |
* |
| 58 |
* @return array The exported routes and nonce's. |
| 59 |
*/ |
| 60 |
public static function export_routes( $categories ) { |
| 61 |
$routes = self::$routes[ $categories ] ?? array(); |
| 62 |
$nonces = self::$nonces[ $categories ] ?? array(); |
| 63 |
|
| 64 |
return array( $routes, $nonces ); |
| 65 |
} |
| 66 |
|
| 67 |
/** |
| 68 |
* Retrieves the namespace for a given module. |
| 69 |
* |
| 70 |
* @param mixed $module The module for which to retrieve the namespace. |
| 71 |
* |
| 72 |
* @return string The namespace for the specified module. |
| 73 |
*/ |
| 74 |
public static function get_namespace( $module ) { |
| 75 |
return 'wp-defender/v1/' . $module; |
| 76 |
} |
| 77 |
} |
| 78 |
|