CurrentRoute.php
100 lines
| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * Request-scoped context for the currently dispatching site route. |
| 5 | * Stores the matched route name and params for Route::is() and related helpers. |
| 6 | * |
| 7 | * @package Framework |
| 8 | * @subpackage Routing |
| 9 | * @since 1.0.0 |
| 10 | */ |
| 11 | namespace Kirki\Framework\Routing; |
| 12 | |
| 13 | \defined('ABSPATH') || exit; |
| 14 | class CurrentRoute |
| 15 | { |
| 16 | /** |
| 17 | * Name of the currently dispatching route. |
| 18 | * |
| 19 | * @var string|null |
| 20 | * |
| 21 | * @since 1.0.0 |
| 22 | */ |
| 23 | protected static $name = null; |
| 24 | /** |
| 25 | * Params for the currently dispatching route. |
| 26 | * |
| 27 | * @var array |
| 28 | * |
| 29 | * @since 1.0.0 |
| 30 | */ |
| 31 | protected static $params = []; |
| 32 | /** |
| 33 | * Set the currently dispatching site route context. |
| 34 | * |
| 35 | * @param string|null $name Route name. |
| 36 | * @param array $params Route params. |
| 37 | * |
| 38 | * @return void |
| 39 | * |
| 40 | * @since 1.0.0 |
| 41 | */ |
| 42 | public static function set($name, array $params = []) |
| 43 | { |
| 44 | static::$name = $name; |
| 45 | static::$params = $params; |
| 46 | } |
| 47 | /** |
| 48 | * Reset the current route context. |
| 49 | * |
| 50 | * @return void |
| 51 | * |
| 52 | * @since 1.0.0 |
| 53 | */ |
| 54 | public static function reset() |
| 55 | { |
| 56 | static::$name = null; |
| 57 | static::$params = []; |
| 58 | } |
| 59 | /** |
| 60 | * Whether the currently dispatching route is the one named $name. |
| 61 | * |
| 62 | * @param string $name Route name. |
| 63 | * |
| 64 | * @return bool |
| 65 | * |
| 66 | * @since 1.0.0 |
| 67 | */ |
| 68 | public static function is(string $name) |
| 69 | { |
| 70 | return static::$name !== null && static::$name === $name; |
| 71 | } |
| 72 | /** |
| 73 | * Get a single param from the currently dispatching route. |
| 74 | * |
| 75 | * @param string $key Param name. |
| 76 | * @param mixed $default Fallback when missing. |
| 77 | * |
| 78 | * @return mixed |
| 79 | * |
| 80 | * @since 1.0.0 |
| 81 | */ |
| 82 | public static function param(string $key, $default = null) |
| 83 | { |
| 84 | return static::$params[$key] ?? $default; |
| 85 | } |
| 86 | /** |
| 87 | * Get all params for the currently dispatching route. |
| 88 | * |
| 89 | * @param mixed $default Fallback when no params are available. |
| 90 | * |
| 91 | * @return mixed |
| 92 | * |
| 93 | * @since 1.0.0 |
| 94 | */ |
| 95 | public static function params($default = []) |
| 96 | { |
| 97 | return !empty(static::$params) ? static::$params : $default; |
| 98 | } |
| 99 | } |
| 100 |