| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentSnippets\App\Services; |
| 4 |
|
| 5 |
class Router |
| 6 |
{ |
| 7 |
private $namespace = ''; |
| 8 |
|
| 9 |
public function __construct($namespace) |
| 10 |
{ |
| 11 |
$this->namespace = $namespace; |
| 12 |
} |
| 13 |
|
| 14 |
public function route($method, $endpoint, $callback, $permissions = []) |
| 15 |
{ |
| 16 |
$endpoint = str_replace('{id}', '(?P<id>[\d]+)', $endpoint); |
| 17 |
|
| 18 |
register_rest_route($this->namespace, $endpoint, array( |
| 19 |
'methods' => $method, |
| 20 |
'callback' => function($request) use ($callback) { |
| 21 |
/* |
| 22 |
* Swallow anything the callback prints — a snippet echoing during |
| 23 |
* validation, a stray warning — so it cannot corrupt the JSON response. |
| 24 |
* |
| 25 |
* This used to be a bare ob_get_clean() after the call, with nothing |
| 26 |
* opening a buffer first. That is harmless when no buffer is active, but |
| 27 |
* when ANOTHER plugin had one open it silently destroyed their buffered |
| 28 |
* output. Now the buffer is opened here and torn down only to the depth |
| 29 |
* it was at on entry, so buffers we did not open are never touched. |
| 30 |
*/ |
| 31 |
$bufferLevel = ob_get_level(); |
| 32 |
|
| 33 |
ob_start(); |
| 34 |
|
| 35 |
try { |
| 36 |
$result = call_user_func($callback, $request); |
| 37 |
} finally { |
| 38 |
while (ob_get_level() > $bufferLevel) { |
| 39 |
ob_end_clean(); |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
if(is_wp_error($result)) { |
| 44 |
return new \WP_REST_Response([ |
| 45 |
'code' => $result->get_error_code(), |
| 46 |
'message' => $result->get_error_message(), |
| 47 |
'data' => $result->get_error_data() |
| 48 |
], 422); |
| 49 |
} |
| 50 |
|
| 51 |
return rest_ensure_response( $result ); |
| 52 |
}, |
| 53 |
'permission_callback' => function($request) use ($permissions) { |
| 54 |
if(is_array($permissions)) { |
| 55 |
// Fail closed: a route registered without any capability is denied |
| 56 |
// rather than served publicly. |
| 57 |
foreach ($permissions as $permission) { |
| 58 |
if(current_user_can($permission)) { |
| 59 |
return true; |
| 60 |
} |
| 61 |
} |
| 62 |
return false; |
| 63 |
} |
| 64 |
|
| 65 |
return call_user_func($permissions, $request); |
| 66 |
} |
| 67 |
)); |
| 68 |
|
| 69 |
return $this; |
| 70 |
} |
| 71 |
|
| 72 |
public function get($endpoint, $callback, $permissions = []) |
| 73 |
{ |
| 74 |
$this->route(\WP_REST_Server::READABLE, $endpoint, $callback, $permissions); |
| 75 |
return $this; |
| 76 |
} |
| 77 |
|
| 78 |
public function post($endpoint, $callback, $permissions = []) |
| 79 |
{ |
| 80 |
$this->route(\WP_REST_Server::CREATABLE, $endpoint, $callback, $permissions); |
| 81 |
return $this; |
| 82 |
} |
| 83 |
} |
| 84 |
|