Jake Vanderwerf
2026-02-08 df6c00db050e188a6bd5707e72c4f1f331ced923
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
<?php
namespace JVBase\rest;
 
use WP_REST_Request;
use WP_Error;
 
if (!defined('ABSPATH')) {
    exit;
}
 
/**
 * Fluent REST Route Builder
 *
 * Usage:
 *   // Single-method routes
 *   Route::for('queue')->get([$this, 'getQueue'])->auth('user');
 *   Route::for('content')->post([$this, 'create'])->auth('verified');
 *
 *   // Multi-method resources
 *   Route::for('uploads')
 *       ->get([$this, 'list'])->auth('user')
 *       ->post([$this, 'upload'])->auth('user')
 *       ->delete(false);
 */
class Route
{
    private string $path;
    private array $methods = [];
    private array $currentMethod = [];
    private bool $registered = false;
 
    private static string $namespace = 'jvb/v1';
    private static ?RateLimits $rateLimiter = null;
 
    // =========================================================================
    // ENTRY POINTS
    // =========================================================================
 
    /**
     * Create a new route builder for the given path
     */
    public static function for(string $path): self
    {
        return new self($path);
    }
 
    /**
     * Set custom namespace (defaults to 'jvb/v1')
     */
    public static function setNamespace(string $namespace): void
    {
        self::$namespace = $namespace;
    }
 
    /**
     * Get current namespace
     */
    public static function getNamespace(): string
    {
        return self::$namespace;
    }
 
    /**
     * Convert readable pattern to WordPress regex
     * Example: 'queue/{id}' becomes 'queue/(?P<id>[a-zA-Z0-9_-]+)'
     */
    public static function pattern(string $path, array $patterns = []): string
    {
        $defaults = [
            'id' => '[a-zA-Z0-9_-]+',
            'slug' => '[a-zA-Z0-9_-]+',
            'type' => '[a-zA-Z_]+',
            'int' => '[0-9]+',
        ];
 
        $patterns = array_merge($defaults, $patterns);
 
        return preg_replace_callback('/\{(\w+)(?::(\w+))?\}/', function($matches) use ($patterns) {
            $name = $matches[1];
            $type = $matches[2] ?? $name;
            $pattern = $patterns[$type] ?? $patterns['id'];
            return "(?P<{$name}>{$pattern})";
        }, $path);
    }
 
    private function __construct(string $path)
    {
        $this->path = '/' . ltrim($path, '/');
    }
 
    // =========================================================================
    // HTTP METHODS
    // =========================================================================
 
    /**
     * Add GET handler
     */
    public function get(callable|array $callback): self
    {
        return $this->addMethod('GET', $callback);
    }
 
    /**
     * Add POST handler
     */
    public function post(callable|array $callback): self
    {
        return $this->addMethod('POST', $callback);
    }
 
    /**
     * Add PUT handler
     */
    public function put(callable|array $callback): self
    {
        return $this->addMethod('PUT', $callback);
    }
 
    /**
     * Add PATCH handler
     */
    public function patch(callable|array $callback): self
    {
        return $this->addMethod('PATCH', $callback);
    }
 
    /**
     * Add DELETE handler (pass false to explicitly disable)
     */
    public function delete(callable|array|false $callback): self
    {
        if ($callback === false) {
            return $this;
        }
        return $this->addMethod('DELETE', $callback);
    }
 
    private function addMethod(string $method, callable|array $callback): self
    {
        // Finalize previous method if exists
        if (!empty($this->currentMethod)) {
            $this->methods[] = $this->currentMethod;
        }
 
        $this->currentMethod = [
            'methods' => $method,
            'callback' => $callback,
            'permission_callback' => '__return_true',
            'args' => [],
        ];
 
        return $this;
    }
 
    // =========================================================================
    // AUTHENTICATION
    // =========================================================================
 
    /**
     * Set authentication requirement
     *
     * @param string|array|callable|false $auth
     *   - 'public' or false: Anyone can access
     *   - 'user': Logged-in user must match 'user' param in request
     *   - 'logged_in': Any logged-in user
     *   - 'admin': Users with manage_options capability
     *   - 'verified': Users with skip_moderation capability
     *   - ['capability' => 'edit_posts']: Specific capability
     *   - ['role' => 'artist']: Specific role
     *   - ['roles' => ['artist', 'admin']]: Multiple roles (OR)
     *   - callable: Custom permission callback
     */
    public function auth(string|array|callable|false $auth): self
    {
        if (empty($this->currentMethod)) {
            return $this;
        }
 
        $this->currentMethod['permission_callback'] = match (true) {
            $auth === false || $auth === 'public'
            => '__return_true',
            $auth === 'logged_in'
            => 'is_user_logged_in',
            $auth === 'user'
            => [PermissionHandler::class, 'userMatch'],
            $auth === 'admin'
            => [PermissionHandler::class, 'isAdmin'],
            $auth === 'verified'
            => [PermissionHandler::class, 'isVerified'],
            $auth === 'nonce' => [PermissionHandler::class, 'nonce'],
            is_callable($auth)
            => $auth,
            is_array($auth) && isset($auth['capability'])
            => fn(WP_REST_Request $req) => current_user_can($auth['capability']),
            is_array($auth) && isset($auth['role'])
            => fn(WP_REST_Request $req) => PermissionHandler::hasRole($req, $auth['role']),
            is_array($auth) && isset($auth['roles'])
            => fn(WP_REST_Request $req) => PermissionHandler::hasAnyRole($req, $auth['roles']),
            default
            => '__return_true',
        };
 
        return $this;
    }
 
    /**
     * Add rate limiting
     */
    public function rateLimit(int $limit = 60, int $window = 60): self
    {
        if (empty($this->currentMethod)) {
            return $this;
        }
 
        $originalCallback = $this->currentMethod['permission_callback'];
 
        $this->currentMethod['permission_callback'] = function(WP_REST_Request $request) use ($originalCallback, $limit, $window) {
            if (self::$rateLimiter === null) {
                self::$rateLimiter = new RateLimits();
            }
 
            if (!self::$rateLimiter->checkLimit($request, $limit, $window)) {
                return new WP_Error(
                    'rate_limit',
                    'Too many requests. Please wait before trying again.',
                    ['status' => 429]
                );
            }
 
            if ($originalCallback === '__return_true') {
                return true;
            }
 
            return is_callable($originalCallback)
                ? call_user_func($originalCallback, $request)
                : true;
        };
 
        return $this;
    }
 
    /**
     * Require nonce verification
     */
    public function nonce(string $action = 'wp_rest', string $header = 'X-WP-Nonce'): self
    {
        if (empty($this->currentMethod)) {
            return $this;
        }
 
        $originalCallback = $this->currentMethod['permission_callback'];
 
        $this->currentMethod['permission_callback'] = function(WP_REST_Request $request) use ($originalCallback, $action, $header) {
            $nonce = $request->get_header($header);
 
            if (!wp_verify_nonce($nonce, $action)) {
                return new WP_Error(
                    'invalid_nonce',
                    'Invalid or expired security token',
                    ['status' => 403]
                );
            }
 
            if ($originalCallback === '__return_true') {
                return true;
            }
 
            return is_callable($originalCallback)
                ? call_user_func($originalCallback, $request)
                : true;
        };
 
        return $this;
    }
 
    // =========================================================================
    // ARGUMENTS
    // =========================================================================
 
    /**
     * Define route arguments with shorthand syntax
     *
     * Examples:
     *   'status' => 'string'
     *   'status' => 'string|required'
     *   'status' => 'string|default:all'
     *   'status' => 'string|enum:pending,completed,failed'
     *   'limit' => 'integer|default:50|min:1|max:100'
     */
    public function args(array $args): self
    {
        if (empty($this->currentMethod)) {
            return $this;
        }
 
        foreach ($args as $name => $definition) {
            $this->currentMethod['args'][$name] = $this->parseArgDefinition($definition);
        }
 
        return $this;
    }
 
    /**
     * Add a single argument
     */
    public function arg(string $name, string|array $definition): self
    {
        if (empty($this->currentMethod)) {
            return $this;
        }
 
        $this->currentMethod['args'][$name] = $this->parseArgDefinition($definition);
        return $this;
    }
 
    private function parseArgDefinition(string|array $definition): array
    {
        if (is_array($definition)) {
            return $definition;
        }
 
        $parts = explode('|', $definition);
        $type = trim($parts[0]);
 
        $arg = [
            'type' => $type === 'int' ? 'integer' : ($type === 'bool' ? 'boolean' : $type),
            'required' => false,
        ];
 
        // Sanitize callback based on type
        $arg['sanitize_callback'] = match ($type) {
            'integer', 'int' => 'absint',
            'string' => 'sanitize_text_field',
            'email' => 'sanitize_email',
            'url' => 'esc_url_raw',
            'boolean', 'bool' => 'rest_sanitize_boolean',
            'array' => function($value) {
                if (is_array($value)) {
                    return $value;
                }
                return [];
            },
            'object' => function($value) {
                if (is_array($value) || is_object($value)) {
                    return (array) $value;
                }
                return [];
            },
            default => null,
        };
 
        // Add validate callback for array/object types
        if (in_array($type, ['array', 'object'])) {
            $arg['validate_callback'] = function($value, $request, $param) {
                // Allow empty arrays/objects
                if (empty($value)) {
                    return true;
                }
                // Ensure it's an array or object
                return is_array($value) || is_object($value);
            };
        }
 
        // Parse modifiers
        foreach (array_slice($parts, 1) as $part) {
            $part = trim($part);
 
            match (true) {
                $part === 'required' => $arg['required'] = true,
                str_starts_with($part, 'default:') => $arg['default'] = $this->castValue(substr($part, 8), $type),
                str_starts_with($part, 'enum:') => $arg['enum'] = array_map('trim', explode(',', substr($part, 5))),
                str_starts_with($part, 'min:') => $arg['minimum'] = (int) substr($part, 4),
                str_starts_with($part, 'max:') => $arg['maximum'] = (int) substr($part, 4),
                str_starts_with($part, 'desc:') => $arg['description'] = substr($part, 5),
                str_starts_with($part, 'pattern:') => $arg['pattern'] = substr($part, 8),
                default => null,
            };
        }
 
        if ($arg['sanitize_callback'] === null) {
            unset($arg['sanitize_callback']);
        }
 
        return $arg;
    }
 
    private function castValue(string $value, string $type): mixed
    {
        return match ($type) {
            'integer', 'int' => (int) $value,
            'boolean', 'bool' => filter_var($value, FILTER_VALIDATE_BOOLEAN),
            'number' => (float) $value,
            'array' => explode(',', $value),
            default => $value,
        };
    }
 
    // =========================================================================
    // REGISTRATION
    // =========================================================================
 
    /**
     * Register the route with WordPress
     */
    public function register(): self
    {
        if ($this->registered) {
            return $this;
        }
 
        if (!empty($this->currentMethod)) {
            $this->methods[] = $this->currentMethod;
            $this->currentMethod = [];
        }
 
        if (empty($this->methods)) {
            return $this;
        }
 
        $config = count($this->methods) === 1 ? $this->methods[0] : $this->methods;
        register_rest_route(self::$namespace, $this->path, $config);
 
        $this->registered = true;
        return $this;
    }
 
    /**
     * Auto-register on destruction
     */
    public function __destruct()
    {
        if (!$this->registered && (!empty($this->methods) || !empty($this->currentMethod))) {
            $this->register();
        }
    }
}