| 1 |
<?php |
| 2 |
|
| 3 |
namespace Elementor\Modules\DesignSystemSync\Classes; |
| 4 |
|
| 5 |
use Exception; |
| 6 |
use WP_REST_Server; |
| 7 |
use WP_REST_Response; |
| 8 |
|
| 9 |
if ( ! defined( 'ABSPATH' ) ) { |
| 10 |
exit; |
| 11 |
} |
| 12 |
|
| 13 |
class Controller { |
| 14 |
const API_NAMESPACE = 'elementor/v1'; |
| 15 |
const API_BASE = 'design-system-sync'; |
| 16 |
const HTTP_CREATED = 201; |
| 17 |
const HTTP_NO_CONTENT = 204; |
| 18 |
const HTTP_INTERNAL_SERVER_ERROR = 500; |
| 19 |
|
| 20 |
public function register_hooks() { |
| 21 |
add_action( 'rest_api_init', [ $this, 'register_routes' ] ); |
| 22 |
} |
| 23 |
|
| 24 |
public function register_routes() { |
| 25 |
register_rest_route( self::API_NAMESPACE, '/' . self::API_BASE . '/stylesheet', [ |
| 26 |
'methods' => WP_REST_Server::CREATABLE, |
| 27 |
'callback' => [ $this, 'generate' ], |
| 28 |
'permission_callback' => [ $this, 'has_permission' ], |
| 29 |
] ); |
| 30 |
} |
| 31 |
|
| 32 |
public function generate(): WP_REST_Response { |
| 33 |
try { |
| 34 |
$stylesheet = new Stylesheet_Manager(); |
| 35 |
$result = $stylesheet->generate(); |
| 36 |
|
| 37 |
if ( null === $result ) { |
| 38 |
return new WP_REST_Response( null, self::HTTP_NO_CONTENT ); |
| 39 |
} |
| 40 |
|
| 41 |
return new WP_REST_Response( $result, self::HTTP_CREATED ); |
| 42 |
} catch ( Exception $e ) { |
| 43 |
return new WP_REST_Response( |
| 44 |
[ 'message' => $e->getMessage() ], |
| 45 |
self::HTTP_INTERNAL_SERVER_ERROR |
| 46 |
); |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
public function has_permission(): bool { |
| 51 |
return current_user_can( 'edit_posts' ); |
| 52 |
} |
| 53 |
} |
| 54 |
|