| 1 |
<?php |
| 2 |
|
| 3 |
namespace Cookiez\Modules\Reviews\Rest; |
| 4 |
|
| 5 |
use Cookiez\Classes\Rest\{ |
| 6 |
Sanitizer, |
| 7 |
Validator, |
| 8 |
}; |
| 9 |
use Cookiez\Modules\Connect\Classes\Config; |
| 10 |
use Cookiez\Modules\Reviews\Classes\Feedback_Client; |
| 11 |
use Cookiez\Modules\Reviews\Classes\Route_Base; |
| 12 |
use Throwable; |
| 13 |
use WP_Error; |
| 14 |
use WP_REST_Request; |
| 15 |
use WP_REST_Response; |
| 16 |
|
| 17 |
if ( ! defined( 'ABSPATH' ) ) { |
| 18 |
exit; // Exit if accessed directly |
| 19 |
} |
| 20 |
|
| 21 |
|
| 22 |
class Feedback extends Route_Base { |
| 23 |
public string $path = 'review'; |
| 24 |
|
| 25 |
public function get_methods(): array { |
| 26 |
return [ 'POST' ]; |
| 27 |
} |
| 28 |
|
| 29 |
public function get_name(): string { |
| 30 |
return 'feedback'; |
| 31 |
} |
| 32 |
|
| 33 |
protected function sanitize_fields(): array { |
| 34 |
return [ |
| 35 |
'feedback' => Sanitizer::textarea(), |
| 36 |
'rating' => Sanitizer::absint(), |
| 37 |
]; |
| 38 |
} |
| 39 |
|
| 40 |
protected function validate_fields(): array { |
| 41 |
return [ |
| 42 |
'rating' => ( new Validator() )->number( [ |
| 43 |
'min' => 1, |
| 44 |
'max' => 5, |
| 45 |
'message' => esc_html__( 'Invalid rating.', 'cookiez' ), |
| 46 |
] ), |
| 47 |
'feedback' => ( new Validator() ) |
| 48 |
->string() |
| 49 |
->nullable(), |
| 50 |
]; |
| 51 |
} |
| 52 |
|
| 53 |
/** |
| 54 |
* @param WP_REST_Request $request |
| 55 |
* |
| 56 |
* @return WP_Error|WP_REST_Response |
| 57 |
*/ |
| 58 |
public function POST( WP_REST_Request $request ) { |
| 59 |
try { |
| 60 |
$error = $this->verify_capability(); |
| 61 |
|
| 62 |
if ( $error ) { |
| 63 |
return $error; |
| 64 |
} |
| 65 |
|
| 66 |
$errors = $this->validate( $this->params ); |
| 67 |
|
| 68 |
if ( ! empty( $errors ) ) { |
| 69 |
return $this->respond_validation_error( $errors ); |
| 70 |
} |
| 71 |
|
| 72 |
$payload = [ |
| 73 |
'feedback' => $this->params['feedback'] ?? '', |
| 74 |
'rating' => $this->params['rating'], |
| 75 |
'app_name' => Config::APP_NAME, |
| 76 |
]; |
| 77 |
|
| 78 |
$response = Feedback_Client::post_feedback( $payload ); |
| 79 |
|
| 80 |
return $this->respond_success_json( $response ); |
| 81 |
|
| 82 |
} catch ( Throwable $t ) { |
| 83 |
return $this->respond_error_json( [ |
| 84 |
'message' => $t->getMessage(), |
| 85 |
'code' => 'internal_server_error', |
| 86 |
], 500 ); |
| 87 |
} |
| 88 |
} |
| 89 |
} |
| 90 |
|